JavaScript String Replace ← Alligator.io | react replace string
Replacingtextinastringisaverycommonoperation,andthank’stothereplacemethodavailableontheStringprototype,it’sveryeasytodo.Thesimplestuse-caseistoprovideastringthatwillactasasubstringtomatchandastringreplacementasthesecondargument:letmyStr=MylittleAlligator🐊;console.log(myStr.replace(Alligator,gator));//Mylittlegator🐊Replaceoperationscanalsobechained:letmyStr=MylittleAlligator🐊;myStr=myStr.replace(Alligator,gator).replace(My,Your).replace(gator🐊,unicorn🦄);console.log(myStr);//Yourlittleunicorn🦄...
Replacing text in a string is a very common operation, and thank’s to the replace method available on the String prototype, it’s very easy to do.
The simplest use-case is to provide a string that will act as a substring to match and a string replacement as the second argument:
let myStr = My little Alligator 🐊; console.log(myStr.replace(Alligator, gator)); // My little gator 🐊Replace operations can also be chained:
let myStr = My little Alligator 🐊; myStr = myStr .replace(Alligator, gator) .replace(My, Your) .replace(gator 🐊, unicorn 🦄); console.log(myStr); // Your little unicorn 🦄Given that strings are immutable in JavaScript, replace returns a new string.
You can use $& in the replacement string to include the match:
let myStr = My little Alligator 🐊; console.log(myStr.replace(gator, -$&-$&)); // My little Alli-gator-gator 🐊Use $` to insert the part of the string that’s before the match.Use $’ to insert the part of...