JavaScript正则表达式模式与变量连接 [英] JavaScript regex pattern concatenate with variable

查看:95
本文介绍了JavaScript正则表达式模式与变量连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何创建与变量连接的正则表达式模式,如下所示:

How to create regex pattern which is concatenate with variable, something like this:

var test ="52";
var re = new RegExp("/\b"+test+"\b/"); 
alert('51,52,53'.match(re));

谢谢

推荐答案

var re = new RegExp("/\b"+test+"\b/"); 

\b 字符串文字是退格字符。将正则表达式放在字符串文字中时,您需要再循环一次:

\b in a string literal is a backspace character. When putting a regex in a string literal you need one more round of escaping:

var re = new RegExp("\\b"+test+"\\b"); 

(您也不需要 // 在这种情况下。)

(You also don't need the // in this context.)

这篇关于JavaScript正则表达式模式与变量连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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