Check if string "is" is javascript with regex

For a very simple JavaScript javascript engine, I need to check if a given string matches "javascript code" (like if-else

, for-loops

or while-loops

). So I am using this very simple expression /(:|=|{|})/g

( tested here ). While this regex works almost anytime, it somehow fails in some cases when I use it in a loop:

// Very simple regex to check if string "is" javascript code
var regFunc = /(:|=|{|})+/g;
// For testing: a simple javascript array
var testArray = [
  // expected: false, is: false
  'string',
  // expected: true, is: true
  'for(var i=0; i<total;i++) {',
  // expected: true, is: false (??)
  '}',
  // expected: true, is: true
  '}'
];

for( var i = 0; i < testArray.length; i++ ) {
  console.log(
    testArray[ i ],
    regFunc.test( testArray[ i ] )
  );
}

      

You can check the console output on JSBin . So I'm wondering why the first "{" outputs false

and the second one outputs true

(which is what I expect for both)?

+3


source to share


1 answer


From MDN - Regex - Test

As with exec (or in combination with it), the test is called multiple times on the same instance of the global regex there will be a previous match.



This means that you will have to reinitialize your regexp object every time you test the string.

+3


source







All Articles