Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript RegExp.test() returns false, even though it should return true

The Prob: I get an AJAX response (JSON or plaintext with line breaks). Each item of the response should be checked via RegEx to find out whether it matches to user-definded patter or not.

Example:

Ajax Response (plain-text)

"Aldor
Aleph
Algae
Algo
Algol
Alma-0
Alphard
Altran"

User-pattern:

/^Alg/ig.test(responseItem)

RegExp Results should look like:

Aldor   // false
Aleph   // false
Algae   // true
Algo    // true
Algol   // true
Alma-0  // false
Alphard // false
Altran  // false

But each time i get different (and kinda weired) results... e.g. (/^alg/ig.test("Algo") => false)

My code:

HTML

...
<form>
  <input id="in" />
</form>
<div id="x">
  Aldor
  Aleph
  Algae
  Algo
  Algol
  Alma-0
  Alphard
  Altran
</div><button id="checker">check!</button>
...

JavaScript (jQuery 1.6.2)

$(function(){
    var $checker = $('#checker');

    $checker.click(function(ev){
        var inputFieldVal = $.trim($('#in').val());
        console.log(inputFieldVal); // Alg
        var regExpPattern = '^'+inputFieldVal,
            re = new RegExp(regExpPattern, 'igm');
        onsole.log(re); // /^Al/gim
        // Get text out of div#x
        var text = $('#x').text();
        // Trim and 'convert' to an array...
            text = $.trim(text).split('\n');
        console.log(text); // ["Aldor", "Aleph", "Algae", "Algo", "Algol", "Alma-0", "Alphard", "Altran"]

        for (var index=0, upper=text.length;index<upper;++index) {
            console.log(
               re.test(text[index]),
               text[index]
             );
        }
    });
})

Console OUTPUT:

/^Alg/ig => should match each item which starts with Alg

false "Aldor"
false "Aleph"
true "Algae"
false "Algo" //Why ? O.o
true "Algol"
false "Alma-0"
false "Alphard"
false "Altran"

/^Al/ig => should match each item because every item start with Al

true "Aldor"
false "Aleph" //Why ? O.o
true "Algae"
false "Algo" //Why ? O.o
true "Algol"
false "Alma-0" //Why ? O.o
true "Alphard"
false "Altran" //Why ? O.o

Any suggestions?

like image 695
V-Light Avatar asked Jul 31 '11 18:07

V-Light


People also ask

What does regex test return?

JavaScript RegExp test() The test() method tests for a match in a string. If it finds a match, it returns true, otherwise it returns false.

What is the purpose of the regex method test ()?

The test() method executes a search for a match between a regular expression and a specified string. Returns true or false .

Which method of RegExp class takes a string argument and returns True False depending on whether the string contains a match of the regular expression?

Using test() The test() method is a RegExp expression method. It searches a string for a pattern, and returns true or false, depending on the result.

Does regex work in JavaScript?

In JavaScript, you can write RegExp patterns using simple patterns, special characters, and flags.


2 Answers

This is a common behavior that the the exec or test methods show when you deal with patterns that have the global g flag.

The RegExp object will keep track of the lastIndex where a match was found, and then on subsequent matches it will start from that lastIndex instead of starting from 0.

For example:

var re = /^a/g;
console.log(re.test("ab")); // true, lastIndex was 0
console.log(re.test("ab")); // false, lastIndex was 1

Remove the g flag from your pattern, since you are looking just for a single match (you are testing each line separately).

like image 185
Christian C. Salvadó Avatar answered Nov 02 '22 07:11

Christian C. Salvadó


You have to remove the global flag "g".

like image 37
Darm Avatar answered Nov 02 '22 06:11

Darm