星期日, 5月 15, 2011

[Javascript] 使用javascript取代所有比對的字串

在javascript的replace函式如果不使用正則表示式的格式的話,只能取代第一個符合的字串規則。
請參考以下這篇文章:

The JavaScript function for String Replace replaces the first occurrence in the string. The function is similar to the php function str_replace and takes two simple parameters. The first parameter is the pattern to find and the second parameter is the string to replace the pattern with when found. The javascript function does not Replace All...

str = str.replace(”find”,”replace”)

To ReplaceAll you have to do it a little differently. To replace all occurrences in the string, use the g modifier like this:
str = str.replace(/find/g,”replace”)

Reference:
JavaScript String Replace All

沒有留言:

張貼留言

留個話吧:)

其他你感興趣的文章

Related Posts with Thumbnails