How to replace all occurrences of a string? | nodejs str replace
![How to replace all occurrences of a string?](https://i.imgur.com/axBPWDg.jpg)
Update:Itssomewhatlateforanupdate,butsinceIjuststumbledonthisquestion,andnoticedthatmypreviousanswerisnotoneImhappywith.Sincethequestioninvolvedreplaceingasingleword,itsincrediblenobodythoughtofusingwordboundaries()acatisnotacaterpillar.replace(/cat/gi,dog);//"adogisnotacaterpillar"Thisisasimpleregexthatavoidsreplacingpartsofwordsinmostcases.However,adash-isstillconsideredawordboundary.Soconditionalscanbeusedinthiscasetoavoidreplacingstringslikecool-cat:acatisnotacool-cat.replace(/cat/g...
![How to replace all occurrences of a string?](http://pix1.agoda.net/hotelimages/300/3008492/3008492_17121510550060424840.jpg?s=800x)
Update:
Its somewhat late for an update, but since I just stumbled on this question, and noticed that my previous answer is not one Im happy with. Since the question involved replaceing a single word, its incredible nobody thought of using word boundaries ()
a cat is not a caterpillar.replace(/cat/gi,dog); //"a dog is not a caterpillar"This is a simple regex that avoids replacing parts of words in most cases. However, a dash - is still considered a word boundary. So conditionals can be used in this case to avoid replacing strings like cool-cat:
a cat is not a cool-cat.replace(/cat/gi,dog);//wrong //"a dog is not a cool-dog" -- nips a cat is not a cool-cat.replace(/(?:([-]))cat(?:([-]))/gi,$1dog$2); //"a dog is not a cool-cat"basically, this question is the same as the question here: Javascript replace " " with " "[1]
@Mike, check the answer I gave there... regexp isnt the only way to replace multiple occurrences of a subsrting, ...
取得本站獨家住宿推薦 15%OFF 訂房優惠
本站住宿推薦 20%OFF 訂房優惠,親子優惠,住宿折扣,限時回饋,平日促銷
How to replace all dots in a string using JavaScript | nodejs str replace
How to replace all occurrences of a string? | nodejs str replace
How to Use the String.prototype.replace() Method JS Example | nodejs str replace
JavaScript replace() 方法 | nodejs str replace
JavaScript replace() 方法 | nodejs str replace
JavaScript String Replace All – 碼人日誌 | nodejs str replace
JavaScript String replace() (字串取代) | nodejs str replace
JavaScript String replace() Method | nodejs str replace
JavaScript | nodejs str replace
node.js string.replace doesn't work? | nodejs str replace
Node.js — String Replace All Appearances | nodejs str replace
Replace a String in a File using Node.js | nodejs str replace
str | nodejs str replace
String Replace in JavaScript | nodejs str replace
String.prototype.replace() | nodejs str replace
String.prototype.replace() | nodejs str replace
`string.replace` doesn't change the variable | nodejs str replace
![](https://i.imgur.com/axBPWDg.jpg)