Looking at this piece of code, can you figure out the result?

'[Log in] ... Log in'.replace('Log', 'Sign')

I suppose you can simply give your answer in no time. it’s '[Sign in] ... Log in'

Wait, shouldn’t it be '[Sign in] ... Sign in' ?

Well, I was confused in the first place like you are. Good for you as you are not fighting alone.

True, it’s a bit confusing that why JavaScript do not replace all the occurrence in the original string. I tried to find out and I consulted to this page.

The definition of replace method is:

The replace() method searches for a match between a substring (or regular expression) and a string, and replaces the matched substring with a new substring

Note, the highlighted substring is not plural. So it’s designed on purpose. Alright, I know that’s not a good and clear reason. But, except it, I really don’t know why the behaviour of replace method is so wicked.

At any rate, we have to tackle this issue. What should we do? Actually, it’s just a piece of cake. The parameter of replace method can accept either a string or a Regex object. So we can input, you guessed it, a Regex instead of string. Here’s the code.

'[Log in] ... Log in'.replace(/Log/g, 'Sign')

Now, you can see the lovely result as expected. So sweet!

 posted on 2011-02-04 21:16  助平君  阅读(1272)  评论(4编辑  收藏  举报