Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass variable to RegExp with word boundary

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 :(

like image 739
srgg6701 Avatar asked Sep 30 '12 17:09

srgg6701


2 Answers

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?

like image 174
Marcus Avatar answered Sep 19 '22 17:09

Marcus


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.
like image 23
JBallin Avatar answered Sep 21 '22 17:09

JBallin