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

Why does global modifier not work properly?

本文关键字:常工作 工作 全局 为什么      更新时间:2023-09-26

为什么"g"修饰符在这种情况下不起作用?我认为用逗号分隔变量并添加"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++;
    }
}

当前演示(仍然不起作用)http://jsfiddle.net/zackarylundquist/NPzfH/

您需要

定义一个实际的RegExp对象。

new RegExp(testcases, 'g');

但请注意,如果字符串包含需要在正则表达式模式中转义的字符,则可能会导致意外结果。

例如

var s = 'test.',
    rx = new RegExp(s);
rx.test('test1'); //true, because . matches almost anything

因此,您必须在输入字符串中对其进行转义。

rx = new RegExp(s.replace(/'./, '''.'));
rx.test('test1'); //false
rx.test('test.'); //true

match() 方法只需要一个参数 - 一个正则表达式对象。要像您尝试的那样从字符串构造正则表达式,请使用 RegExp 构造函数:

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

然后你可以做:

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