Skip to content

Instantly share code, notes, and snippets.

@nfroidure
Last active December 12, 2015 01:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nfroidure/4692419 to your computer and use it in GitHub Desktop.
Save nfroidure/4692419 to your computer and use it in GitHub Desktop.
RegExp inconsistency ?
var str="<h2>Blahblah</h2><p>Blahblah Blahblah Blahblah.</p><h2>Blahblah</h2><p style=\"text-align: center;\"> <img alt=\"Blahblah\" src=\"http://www.example.com/images/blah.jpg\" /></p><p>BlahblahBlahblah Blahblah Blahblah.</p><h2>Blahblah</h2><p>Blahblah</p>";
var regExp=new RegExp('<([^>]+)"([^>]*)>','mg');
var pattern='<$1$2>';
while(regExp.test(str))
str = str.replace(regExp, pattern);
console.log(str);
// outputs
// <h2>Blahblah</h2><p>Blahblah Blahblah Blahblah.</p><h2>Blahblah</h2><p style=text-align: center;> <img alt="Blahblah" src=http://www.example.com/images/blah.jpg /></p><p>BlahblahBlahblah Blahblah Blahblah.</p><h2>Blahblah</h2><p>Blahblah</p>
// Notice the " in the img alt attribute
var str="<h2>Blahblah</h2><p>Blahblah Blahblah Blahblah.</p><h2>Blahblah</h2><p style=\"text-align: center;\"> <img alt=\"Blahblah\" src=\"http://www.example.com/images/blah.jpg\" /></p><p>BlahblahBlahblah Blahblah Blahblah.</p><h2>Blahblah</h2><p>Blahblah</p>";
var regExp=new RegExp('<([^>]+)"([^>]*)>','mg');
var pattern='<$1$2>';
while(regExp.test(str))
str = str.replace(regExp, pattern);
str = str.replace(regExp, pattern); // Executing the same regExp without testing before
str = str.replace(regExp, pattern); // Executing the same regExp without testing before
console.log(str);
// outputs
// <h2>Blahblah</h2><p>Blahblah Blahblah Blahblah.</p><h2>Blahblah</h2><p style=text-align: center;> <img alt=Blahblah src=http://www.example.com/images/blah.jpg /></p><p>BlahblahBlahblah Blahblah Blahblah.</p><h2>Blahblah</h2><p>Blahblah</p>
// Nor more " while the Regular expression hasn't changed
// What is the difference between RegExp.test() and String.replace() ??
@nfroidure
Copy link
Author

Submitted a bug to Chromium project http://code.google.com/p/chromium/issues/detail?id=173668

@nfroidure
Copy link
Author

@nfroidure
Copy link
Author

It seems it's a normal behavior thanks to the mozilla issue reply. Did a blog post about that : http://www.insertafter.com/articles-subtilites_de_regexp.html

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment