Forum Discussion

Poida's avatar
Poida
Occasional Contributor
6 years ago
Solved

Find and Replace with Regular Expression in Script using Javascript

Hi, i'm having trouble with doing a find and replace using regex on a string in a script using Javascript.

 

The idea is to get rid of all multiple consecutive white space characters in the string and leave only single spaces in their place .... so....      |  this  has      too      much |      would become     | this has too much |

 

My plan was to just locate anywhere where there's 2 or more whitespaces and replace them with a single whitespace.  I couldn't figure out the {2,} style to say 2 or more then I got tangled up and now I'm here.

Below is test code to demonstrate:

  var regEx;
  var ResStr = "";
  var Instr = "   Words   with too much  space    |";
  regex = "\b+";
  ResStr = Instr.replace(regEx,' ');
  BuiltIn.ShowMessage(ResStr);

The result is an unaltered string.  The goggles.... they do nothing...

Any tips on where I'm going wrong?

Pete :)

  • Poida's avatar
    Poida
    6 years ago

    Thanks tristaanogre,  that tipped me off.  Needed the gi switch at the end to work and it was using the javascript re syntax not the native testcomplete one.  Below is the working code. 

     

    function UseRegex()
      {
        var regex = /\s+/gi;
        var Instr = "    Words    with too much space    |";
        var ResStr = Instr.replace(regex," ");   
        Log.Message(ResStr); 
      }

3 Replies

  • tristaanogre's avatar
    tristaanogre
    Esteemed Contributor

    I THINK it's because you're not actually creating a regEx but using a string... 

    Now, I didn't get the regEx to find ALL the extra spaces... I'm not so well versed in the syntax to figure that out.... but this gave some partial success.

     

    function yaditty(){
      var regEx;
      var ResStr = "";
      var Instr = "   Words   with too much  space    |";
      regEx = /\b +\b/;
      ResStr = Instr.replace(regEx, ' ');
      Log.Message(Instr);
      Log.Message(ResStr);
    }
    • Poida's avatar
      Poida
      Occasional Contributor

      Thanks tristaanogre,  that tipped me off.  Needed the gi switch at the end to work and it was using the javascript re syntax not the native testcomplete one.  Below is the working code. 

       

      function UseRegex()
        {
          var regex = /\s+/gi;
          var Instr = "    Words    with too much space    |";
          var ResStr = Instr.replace(regex," ");   
          Log.Message(ResStr); 
        }