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 :)
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); }