Last active
December 12, 2015 01:38
-
-
Save nfroidure/4692419 to your computer and use it in GitHub Desktop.
RegExp inconsistency ?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() ?? |
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
Submitted a bug to Chromium project http://code.google.com/p/chromium/issues/detail?id=173668