2

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 );

    }
2
  • 1
    Could you please post your code including the regular expression being used and the text that is being matched? Unclear what is causing this from the provided screenshot... Commented Jan 9, 2014 at 12:39
  • could you please share your code and which browser you are using with version. Commented Jan 9, 2014 at 12:40

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

3 Comments

What a wonderful and simple explanation. It works! Thank you very much.
When you do .exec() you can do string.match(regex) which will return you the whole array of occurences so you will be able to iterate through the array and inspect more easily :)
You could also do it like this: var res; while (res = re.exec(s)) { // do something with each result, maybe add to an array }.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.