I have to pass to RegExp value of variable and point a word boundary. I have a string to be checked if it contains a variable value. I don't know how to pass to regexp as a variable value and a word boundary attribute.
So something like this:
var sa="Sample";
var re=new RegExp(/\b/+sa);
alert(re.test("Sample text"));
I tried some ways to solve a problem but still can't do that :(
I have to pass to RegExp value of variable and point a word boundary. I have a string to be checked if it contains a variable value. I don't know how to pass to regexp as a variable value and a word boundary attribute.
So something like this:
var sa="Sample";
var re=new RegExp(/\b/+sa);
alert(re.test("Sample text"));
I tried some ways to solve a problem but still can't do that :(
Share Improve this question edited Jan 11, 2014 at 18:13 nhahtdh 56.8k15 gold badges129 silver badges164 bronze badges asked Sep 30, 2012 at 17:15 srgg6701srgg6701 2,0486 gold badges24 silver badges37 bronze badges2 Answers
Reset to default 16Use this: re = new RegExp("\\b" + sa)
And as @RobW mentioned, you may need to escape the sa
.
See this: Is there a RegExp.escape function in Javascript?
If you want to get ALL occurrences (g
), be case insensitive (i
), and use boundaries so that it isn't a word within another word (\\b
):
re = new RegExp(`\\b${sa}\\b`, 'gi');
Example:
let inputString = "I'm John, or johnny, but I prefer john.";
let swap = "John";
let re = new RegExp(`\\b${swap}\\b`, 'gi');
console.log(inputString.replace(re, "Jack")); // I'm Jack, or johnny, but I prefer Jack.