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 :(
Use 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With