سؤال

Why does the "g" modifier not work in this instance? I thought separating a variable with a comma and adding "g" was an acceptable way to set the match to a global match?

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/

هل كانت مفيدة؟

المحلول

You need to define an actual RegExp object.

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.

E.g

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. To construct a regexp from a string like you're trying to do use the RegExp constructor:

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

Then you can do:

if (str.match(testcases).length >= 2) {
    console.log(testcases);
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top