10

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

nhahtdh
  • 55,989
  • 15
  • 126
  • 162
srgg6701
  • 1,878
  • 6
  • 23
  • 37

2 Answers2

16

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?

Community
  • 1
  • 1
Marcus
  • 6,701
  • 4
  • 19
  • 28
8

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.
JBallin
  • 8,481
  • 4
  • 46
  • 51
  • Your answer is the closest thing to what I'm on the hunt for. What is the quotes you're using, where is the documentation to pipe in variables with `${swap}` – Alexander Dixon Aug 27 '18 at 22:15
  • @AlexanderDixon are you asking about [template literals](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals)? – JBallin Aug 27 '18 at 22:26
  • `element_text.match(new RegExp(matching_option_text, 'gi'))` I want to pass the "matching_option_text" variables with the `^$` start and end delimiter. – Alexander Dixon Aug 27 '18 at 22:28
  • here is a better representation of what I'm asking. https://stackoverflow.com/q/52047817/5076162 – Alexander Dixon Aug 27 '18 at 22:40
  • I don't see `\\b${swap}\\b` working in my phpstorm editor - I just get a red underscore - is this actually javascript? Is there a pure javascript version of this? – user1432181 Jul 29 '22 at 16:00
  • @user1432181 It's regular JavaScript. See template literals link above. – JBallin Jul 29 '22 at 17:43
  • My mistake - phpstorm was showing .php embedding Javascript; if I put the code into a pure js file then it works. – user1432181 Jul 29 '22 at 19:41