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
  • 54,546
  • 15
  • 119
  • 154
srgg6701
  • 1,748
  • 4
  • 21
  • 37

2 Answers2

14

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,445
  • 3
  • 18
  • 27
7

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
  • 6,568
  • 1
  • 40
  • 45
  • 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