通过单词边界将变量传递给RegExp [英] Pass variable to RegExp with word boundary

查看:50
本文介绍了通过单词边界将变量传递给RegExp的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须将变量的RegExp值传递给一个单词边界.我有一个字符串要检查是否包含变量值.我不知道如何将regexp作为变量值和单词边界属性传递给我们.

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.

是这样的:

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

推荐答案

使用此方法: re = new RegExp("\\ b" + sa)

正如@RobW所述,您可能需要转义 sa .

And as @RobW mentioned, you may need to escape the sa.

查看此内容: JavaScript中是否存在RegExp.escape函数?

这篇关于通过单词边界将变量传递给RegExp的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆