Notes & Commentary

Smaller thoughts and bits not big enough for the Front Page.

Quirks with JavaScript String .replace() and regular expressions

June 4th, 2009 · 4 Comments

I was doing a global replace on a string using JavaScript String’s .replace() method, and I saw some funny behavior I thought was worth noting.

Given the following sample code, what do you expect the output to be? (Hint: notice the whitespace in the string and regex)

var str="Visit Microsoft Microsoft Microsoft !";
document.write(str.replace(/ Microsoft /g," W3Schools "));

Until today, I was expecting: “Visit W3Schools W3Schools W3Schools !” but wouldn’t you know it, the result is actually “Visit W3Schools Microsoft W3Schools !”

All of you regular expression ninjas probably knew that already, but it was news to me! :-)

Post to Twitter Tweet This

Tags: other

4 responses so far ↓

  • 1 John Lascurettes // Jun 4, 2009 at 10:27 pm

    Right. Did you learn your lesson and go for /\bMicrosoft\b/g? ;)

  • 2 John Lascurettes // Jun 4, 2009 at 10:40 pm

    Another, probably better choice would have been:

    / Microsoft(?= )/g because that would not have gotten a false positive on something like “Microsoft-ish” like my first example would have.

    The lookahead is a zero-position match, meaning, it would still leave the space to be used by the next positive match.

  • 3 Adam Wulf // Jun 4, 2009 at 11:42 pm

    Ha! sadly I did not learn my lesson and use \b :P but I’ll try that out tomorrow b/c its significantly more correct than what I did to fix it.

    I ran into this trying to wrap misspellings in Jive’s editor with tags to show the red underline. I had to match all non-alpha characters between words, not just whitespace, so I’m not sure if \b will work? maybe the lookahead will though…

    my solution is hard enough for me to describe in person, let alone in a comment / blog post (which is probably a red flag anyways!), but I’ll show you tomorrow at work if you’re curious :-)

  • 4 блочная вёрстка сайта // Aug 19, 2010 at 8:26 am

    Здравствуйте, заметил небольшую погрешнсть в вёрстке вашего блога, если хотите поправлю. О цене не беспокойтесь, мне Ваш ресурс понравился, так что сделаю бесплатно!

Leave a Comment or