Friday, October 7, 2011

Problem with javascript replace() function

Suppose we have a string: "The horse kicks the stony horse". Using javascript replace() function, we want to replace 'horse' by 'cow'.

    str = "The horse kicks the stony horse";
    replaced_str = str.replace('horse', 'cow');

and the result of replaced_str is "The cow kicks the stony horse" ... surprise!

The replace() function replaced only the first string which was found and ignore others. What we should do?

Regex is a way to solve it, instead
    replaced_str = str.replace('horse', 'cow');
We use
    replaced_str = str.replace(/horse/g, 'cow');

and the replaced_str should be "The cow kicks the stone cow".

No comments:

Post a Comment