Wednesday, 11 September 2013

replace() does not take into consideration the "g" flag when used with string instead of regex

replace() does not take into consideration the "g" flag when used with
string instead of regex

var a = 'Construction,Airports,Construction|Commercial
Construction,Construction|Education,Construction|Healthcare,Construction|Housing,Construction|Industrial
Construction,Construction|Other,Construction|Ports,Construction|Rail,Construction|Residential
Construction,Construction|Roads & Bridges,Social Infrastructure|Commercial
Construction,Social Infrastructure|Education,Social
Infrastructure|Healthcare,Social Infrastructure|Housing,Social
Infrastructure|Other,Social Infrastructure|Residential Construction';
alert(a.replace('|', ',', 'g'));
On chrome, it is replacing only the first occurrence of |, while using the
g flag in the regex form of the replace() function, it replaces all the
occurrences:
alert(a.replace(/\|/g, ',', 'g'));
Can anyone please help me understand if I'm doing something wrong in the
first form of the replace? is that the intended behavior or is it a bug?

No comments:

Post a Comment