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
Solved! Go to Solution.
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); }
Hi @peridde,
If you need to remove extra spaces, you can simply call the aqString.Trim method. The article below contains the description of this method, as well as useful examples:
https://support.smartbear.com/testcomplete/docs/reference/program-objects/aqstring/trim.html
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); }
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); }
User | Count |
---|---|
61 | |
12 | |
11 | |
10 | |
9 |
Subject | Author | Latest Post |
---|---|---|