Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if string "is" javascript code with regex

For a very simple javascript template engine I need to check whether a given string "is" javascript code (like if-else,for-loops or while-loops). Therefore I'm using this very simple regex /(:|=|{|})/g ("tested" here). While this regex works almost anytime it somehow fails in some cases when I'm using 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)?

like image 673
Daniel Avatar asked Jul 28 '26 15:07

Daniel


1 Answers

From MDN - Regex - Test

As with exec (or in combination with it), test called multiple times on the same global regular expression instance will advance past the previous match.

This mean you'll have to reinitialize your regexp object each time you're testing a string.

like image 106
blue112 Avatar answered Jul 30 '26 04:07

blue112



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!