当使用正则表达式限制在文本区域中输入 HTML 实体时,我遇到了一个问题。
我使用了这个正则表达式 - /<(.|\n)*?>/g;
对于限制 HTML 实体,它对我来说工作得很好,但是当我声明全局变量并使用这个正则表达式时,它每次都会给我不同的 - 不同的测试用例(真/假)。
有一个 Jsfiddle - Try This
当您第一次单击“提交”按钮时,对于相同的内容,您会得到“true”,第二次会得到“false”。
谁能告诉我为什么我的正则表达式每次在全局声明它时都会返回不同的测试用例?
感谢您的帮助......!!!
最佳答案
这是因为您在正则表达式上使用了 g
标志。
如果您需要使用g
,您可以在函数内定义您的正则表达式,这样您每次都会得到一个新的
function CheckContent(){
var RegForRestrictHtmlTags2 = /<(.|\n)*?>/g;
$('#txtJobDesc').val("AAAAAAAA<fff>AAAAAA");
alert(RegForRestrictHtmlTags2.test($('#txtJobDesc').val()));
}
使用 g
标志时,您可以使用 .test
查找主题字符串中的多个匹配项。 .test
将继续为每个唯一匹配返回 true
。一旦 .test
返回 false,它将有效地“重置”到起始位置。
考虑这个简单的例子
> var re = /a/g;
undefined
> var str = 'aaaaab';
undefined
> re.test(str); // first a
true
> re.test(str); // second a
true
> re.test(str); // third a
true
> re.test(str); // fourth a
true
> re.test(str); // fifth a
true
> re.test(str); // no more a's; reset
false
> re.test(str); // back to first a
true
关于javascript - 为什么 jquery 正则表达式每次返回不同的测试用例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18842489/