Find and replace substring within a string using replace
.
If you know the exact substring use it directly in replace
and be at peace.
1
2
3
|
let sample = "Lorem ipsum dolor sit amet ...";
sample = sample.replace("ipsum", "gypsum");
console.log("sample: ", sample); // Lorem gypsum dolor sit amet ...
|
Or, use regular expressions and the massive advantages that come with it.
1
2
|
sample = sample.replace(/Lorem/gi, "loremi");
console.log("sample: ", sample); // loremi ipsum dolor sit amet ...
|
If you have special characters that cannot be handled by regular expressions.
1
2
3
|
let sample = "Lorem ipsum dolor sit amet ...";
sample = sample.split("sit").join("kit");
console.log("sample: ", sample); // Lorem ipsum dolor kit amet ...
|