简体   繁体   English

为什么全局修饰符无法正常工作?

[英]Why does global modifier not work properly?

Why does the "g" modifier not work in this instance? 为什么“ g”修饰符在这种情况下不起作用? I thought separating a variable with a comma and adding "g" was an acceptable way to set the match to a global match? 我认为用逗号分隔变量并添加“ g”是将匹配设置为全局匹配的可接受方法吗?

str = "cabeca";
testcases = [];
x = 0;
for (i = 0; i < str.length; i++) {
testcases = str[i];
    x = i + 1;
    while (x < str.length) {
            testcases += "" + str[x];
            if (str.match((testcases),"g").length >= 2) {
            console.log(testcases);
            }
        x++;
    }
}

Current demo (still not working) http://jsfiddle.net/zackarylundquist/NPzfH/ 当前演示(仍然无法正常工作) http://jsfiddle.net/zackarylundquist/NPzfH/

You need to define an actual RegExp object. 您需要定义一个实际的RegExp对象。

new RegExp(testcases, 'g');

However be advised that if your string contains characters that needs to be escaped in a regular expression pattern, it could lead to unexpected results. 但是请注意,如果您的字符串包含需要以正则表达式模式进行转义的字符,则可能导致意外结果。

Eg 例如

var s = 'test.',
    rx = new RegExp(s);

rx.test('test1'); //true, because . matches almost anything

Therefore, you would have to escape it in the input string. 因此,您将不得不在输入字符串中对其进行转义。

rx = new RegExp(s.replace(/\./, '\\.'));

rx.test('test1'); //false
rx.test('test.'); //true

The match() method only expects one argument - a regexp object. match()方法仅需要一个参数-一个regexp对象。 To construct a regexp from a string like you're trying to do use the RegExp constructor: 如要尝试从字符串构造regexp,请使用RegExp构造函数:

testcases = new RegExp(str[i],'g');

Then you can do: 然后,您可以执行以下操作:

if (str.match(testcases).length >= 2) {
    console.log(testcases);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM