使用正则表达式匹配动态字符串 [英] Match dynamic string using regex

查看:256
本文介绍了使用正则表达式匹配动态字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试检测字符串中字符串的出现。但是下面的代码总是返回null。显然出了问题,但由于我是新手,我无法发现它。我期待代码返回true而不是null

I'm trying to detect an occurrence of a string within string. But the code below always returns "null". Obviously something went wrong, but since I'm a newbie, I can't spot it. I'm expecting that the code returns "true" instead of "null"

var searchStr = 'width'; 
var strRegExPattern = '/'+searchStr+'\b/'; 
"32:width: 900px;".match(new RegExp(strRegExPattern,'g'));


推荐答案

通过时请不要放'/' RegExp选项中的字符串

Please don't put '/' when you pass string in RegExp option

以下情况可以正常

var strRegExPattern = '\\b'+searchStr+'\\b'; 
"32:width: 900px;".match(new RegExp(strRegExPattern,'g'));

这篇关于使用正则表达式匹配动态字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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