带有可变字符串的javascript正则表达式模式不起作用 [英] javascript regex pattern with a variable string not working
本文介绍了带有可变字符串的javascript正则表达式模式不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试创建一个将一些参数传递给正则表达式脚本的函数:
I am trying to create a function that will pass some parameters to a regex script:
function classAttributes( classString, className ) {
var data;
var regex = new RegExp(className+"\[(.*?)\]");
var matches = classString.match(regex);
if ( matches ) {
//matches[1] refers to options inside [] "required, email, ..."
var spec = matches[1].split(/,\s*/);
if ( spec.length > 0 ) {
data = spec;
}
}
return data;
}
但是由于某种原因,它不喜欢我传递给它的字符串变量"new RegExp(className +" [(.*?)]);" 它不会引发错误,但是验证不起作用.
but for some reason it doesnt like the string variable that I pass it "new RegExp(className+"[(.*?)]");" it doesnt throw an error but the validation doesnt work.
我将从类stribute中获取信息,并将其作为classString传递
I will take the information from the class stribute and pass it as classString
<div class="field-character-count test[asd, 123, hello]"></div>
和"className"将代表测试"
and the "className" will represent "test"
推荐答案
我认为您需要在搜索字符串中转义反斜杠-
I think you need to escape the backslashes inside the search string -
var regex = new RegExp(className+"\\[(.*?)\\]");
这篇关于带有可变字符串的javascript正则表达式模式不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文