close
轉自 https://vinixwu.wordpress.com/2017/05/23/how_to_replace_all_occurance_of_string_in_javascript/
--
打習慣C#,在Javascript中想要取代字串中的指定pattern,下意識地就會打 str.replace(“pattern", “string to find"),但是瀏覽器的replace其實是半殘的,它只會取代找到的第一個pattern,例如:
1
|
"Dog is cute. Dog is happy." .replace( "Dog" , "Cat" ); |
,會得到"Cat is cute. Dog is happy."。
上網找了一下文件,發現要取代所有pattern,就只能使用Regular Expression(用/來開頭及結尾),再加上全域表示符g。像上例就必須改成:
1
|
"Dog is cute. Dog is happy." .replace(/Dog/g, "Cat" ); |
,才會是想要的結果。
結果為了這個語言上的差異,浪費了一個小時debug。 Orz
--
全站熱搜