最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Pass variable to RegExp with word boundary - Stack Overflow

programmeradmin6浏览0评论

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 badges
Add a comment  | 

2 Answers 2

Reset to default 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?

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.
发布评论

评论列表(0)

  1. 暂无评论