Reputation: 121
I wrote some regexp. It works when I execute it with string typed in console, but not in some cases in my script.
Here is my console output:
>body
["VERSION:2.1", "N:;S Wicius;;;", "FN:S Wicius", "TEL;PREF;CELL:000000000"]
>records.line
/^([^:;]+)(?:;([^:]+))?:(.+)$/gm
>records.line.exec( body[1] )
null
>body[1] == "N:;S Wicius;;;"
true
>records.line.exec( "N:;S Wicius;;;" )
["N:;S Wicius;;;", "N", undefined, ";S Wicius;;;"]
>for( var i = 0; i < body.length; i++ ) {
var line = [];
if( line = records.line.exec( body[i] ) )
console.log( line )
}
["VERSION:2.1", "VERSION", undefined, "2.1"]
["FN:S Wicius", "FN", undefined, "S Wicius"]
Upvotes: 1
Views: 141
Reputation: 4499
Well, the problem is caused by the combination of the following factors:
exec
method changes lastIndex property of your regexp objectlastIndex is a read/write property of RegExp objects. For regular expressions with the "g" attribute set, it contains an integer that specifies the character position immediately following the last match found by the RegExp.exec( ) and RegExp.test( ) methods. These methods use this property as the starting point for the next search they conduct.
This property allows you to call those methods repeatedly, to loop through all matches in a string and works only if the "g" modifier is set.
You can fix the issue by changing any of these 3 conditions (you also could manually reset records.line.lastIndex = 0
in each iteration). Your /g modifier seems to be useless, so just get rid of it.
Upvotes: 1
Reputation: 183311
It looks like body[1]
is not actually a string, but rather, is an object whose "ToPrimitive" operation yields "N:;S Wicius;;;"
. So although body[1] == "N:;S Wicius;;;"
is true
(as you saw), body[1] === "N:;S Wicius;;;"
will be false
.
If you want to perform your regex-match on the string-value of body[1]
, you can do this:
records.line.exec( '' + body[1] )
Upvotes: 0