How to prevent regular expression test toggling when using a variable? [duplicate] - javascript

This question already has answers here:
Unexpected Javascript RegExp behavior [duplicate]
(3 answers)
Closed 8 years ago.
I just noticed the following strange behavior (both in browsers and nodejs:
> a = /^\/foo/g
/^\/foo/g
> a.test("/foo")
true
> a.test("/foo")
false
> a.test("/foo")
true
> a.test("/foo")
false
> a.test("/foo")
true
What kind of mad science we have here? How can I prevent this behavior?
I just want to have a regex variable that checks if a string matches the pattern globally.
Documentation pages don't seem to bring some light there... I'd really appreciate a link to documentation references.

Set the lastIndex of your regex to 0 after each test.
a = /^\/foo/g
a.test("/foo"); //true
a.test("/foo"); //false
a.test("/foo"); //true
a.lastIndex = 0; //reset the index to start the next match at beginning
a.test("/foo"); //true

Related

Why does this semi-colon cause a incorrect falsey result [duplicate]

This question already has answers here:
Why does a RegExp with global flag give wrong results?
(7 answers)
Closed 7 years ago.
Strange truth test results
filter = /rob/gi
>> /rob/gi
filter.test('hey')
>> false
filter.test('rob')
>> true
true && filter.test('rob');
>> false
true && filter.test('rob') ;
>> true
(true && filter.test('rob'));
>> false
(true && filter.test('rob')) ;
>> true
Reproducible in Firefox and Chrome
That's because .test behaves as .exec() and maintains state (position) between calls
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.
So for the 'rob' input it matches it. Then on the second call it tries to match whatever left after the first match: it's an empty string, so it fails and rewinds.
To see it in action try to match 'robrobrob' - there will be 3 true followed by false.
References:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/test
UPD:
In this particular case it happens because you use the g modified (credits to Barmar)

Regex'es weird behavior when doing Regex.exec(testString) [duplicate]

This question already has answers here:
Regex.prototype.exec returns null on second iteration of the search [duplicate]
(2 answers)
Closed 8 years ago.
May I know why the following weird behavior happening for the below statements?
a = /\d+/gi
outputs `/\d+/gi`
a.exec('test1323')
outputs `["1323"]`
and again running the same statements gives
a.exec('test1323')
null
Even I tried creating regex using new Regex("regex string"), but still no change.
Please see the attachment
It happens in chrome console.
You are creating a regexp with the g flag. When you do that, the exec method remembers the position of the last match and matching starts from the last match. The results are explained below:
> a = /\d+/gi
< /\d+/gi // a.lastIndex is initialized to 0
> a.exec("test1323")
< ["1323"] // match begins at 0, match found at index 4...7, a.lastIndex is now 8
> a.exec("test1323")
< null // match begins at 8, no match found, a.lastIndex is reset to 0
> a.exec("test1323")
< ["1323"] // match begins at 0, match found at index 4...7, a.lastIndex is now 8
A longer dry run of similar problem can be found in this answer.

Length regex tests true on null [duplicate]

This question already has answers here:
Is it a bug in Ecmascript - /\S/.test(null) returns true?
(2 answers)
Closed 9 years ago.
I need to verify that an input is between 1 and 512 characters long. I'm using the standard length-check regex of /^.{1,512}$/. When I run
/^.{1,512}$/.test(null)
it returns true. How do I get a length-check regex to fail against null? And why does this test true against null in the first place?
EDIT: Leaving this here since it's more googleable in my case than the earlier question, but per here, the problem is that the regex coerces null into 'null' before testing.
I would test with a regex like this:
var myregexp = /^(?!null).{1,512}$/m;;

Comma separated number/function in parenthesis in JavaScript? [duplicate]

This question already has answers here:
What does the comma operator do in JavaScript?
(5 answers)
Closed 6 years ago.
I read a line from doT.js:
var global = (function(){ return this || (0||eval)('this'); }());
After it was minified:
l=function(){return this||(0,eval)("this")}();
So what is the (0,eval), I mean what does the comma do?
I played in Chrome's console, (0,1), (2,1), (2,{}), 2,1, etc, it always returns the last one.
The comma operator evaluates both and always returns the last. Much like you said.
You can read up on the comma operator: http://javascriptweblog.wordpress.com/2011/04/04/the-javascript-comma-operator/
Even though I have no idea the purpose of (0||eval)... (0,eval) is the equivalent and one less character.

why does my javascript regex.test() give alternating results [duplicate]

This question already has answers here:
Why does a RegExp with global flag give wrong results?
(7 answers)
Closed 5 years ago.
Possible Duplicate:
Javascript regex returning true.. then false.. then true.. etc
var r = /\d/g;
var a = r.test("1"); // will be true
var b = r.test("1"); // will be false
console.log(a == b); // will be false
Please explain to me why the result of r.test("1") alternates with each call?
I was able to work around the issue I was having by removing the g modifier. However I would still like to understand why this happens.
When you're using /g, the regex object will save state between calls (since you should be using it to match over multiple calls). It matches once, but subsequent calls start from after the original match.
(This is a duplicate of Javascript regex returning true.. then false.. then true.. etc)

Categories

Resources