为什么jquery正则表达式返回不同 - 每次都有不同的测试用例?

Ish*_*ain 2 javascript regex jquery

当使用Regexp for restrict将HTML实体输入文本区域时,我遇到了问题.

我使用这个Regexp - /<(.|\n)*?>/g; 限制HTML实体,它对我来说很好,但是当我声明全局变量并使用这个正则表达式时,它每次都给我不同的 - 不同的测试用例(真/假).

有一个Jsfiddle - 试试这个

当你第一次点击"提交"按钮时你得到"真实",第二次你得到"假"相同的内容.

任何人都可以告诉我为什么我的正则表达式返回不同 - 每次在全局声明时都会有不同的测试用例吗?

谢谢您帮忙...!!!

Tha*_*you 7

这是因为你在gRegExp上使用了这个标志.

如果需要使用g,可以在函数内定义正则表达式,这样每次都可以获得一个新的正则表达式

function CheckContent(){
  var RegForRestrictHtmlTags2 = /<(.|\n)*?>/g;  
  $('#txtJobDesc').val("AAAAAAAA<fff>AAAAAA");
  alert(RegForRestrictHtmlTags2.test($('#txtJobDesc').val()));
}
Run Code Online (Sandbox Code Playgroud)

使用该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
Run Code Online (Sandbox Code Playgroud)