Michael Sazonov
Michael Sazonov

Reputation: 1533

Unexpected behavior of regexp in JavaScript

I've encountered this weird behavior:enter image description here

I'm on a breakpoint (variables don't change). At the console you can see, that each time I try to evaluate regexp methods on the same unchanging variable "text" I get these opposite responses. Is there an explanation for such thing?

The relevant code is here:

this.singleRe = /<\$([\s\S]*?)>/g;    

while( this.singleRe.test( text ) ){
        match = this.singleRe.exec( text );

        result = "";

        if( match ){

            result = match[ 1 ].indexOf( "." ) != -1 ? eval( "obj." +  match[ 1 ] ) :  eval( "value." + match[ 1 ] );

        }

        text = text.replace( this.singleRe , result );

    }

Upvotes: 2

Views: 85

Answers (1)

lukas.pukenis
lukas.pukenis

Reputation: 13597

When you use regex with exec() and a global flag - g, a cursor is changing each time, like here:

var re = /\w/g;
var s = 'Hello regex world!'

re.exec(s); // => ['H']
re.exec(s); // => ['e']
re.exec(s); // => ['l']
re.exec(s); // => ['l']
re.exec(s); // => ['o']

Note the g flag! This means that regex will match multiple occurencies instead of one!

EDIT

I suggest instead of using regex.exec(string) to use string.match(regex) if possible. This will yield an array of occurences and it is easy to inspect the array or to iterate through it.

Upvotes: 4

Related Questions