replace a substring in a string in javascript

To replace a substring in a string in JavaScript, you can use the replace() method on the string. The replace() method takes two parameters - the substring to be replaced, and the new substring to replace it with.

Here is an example code snippet that replaces all occurrences of a specific substring in a string using the replace() method:

index.tsx
let originalString = "The quick brown fox jumps over the lazy dog";
let newString = originalString.replace("brown", "red");
console.log(newString); // Output: "The quick red fox jumps over the lazy dog"
203 chars
4 lines

In the above example, the replace() method replaces the first occurrence of the substring "brown" with the new substring "red".

If you want to replace all occurrences of the substring in the string, you can use a regular expression with the g (global) flag:

index.tsx
let originalString = "The quick brown fox jumps over the lazy dog";
let newString = originalString.replace(/brown/g, "red");
console.log(newString); // Output: "The quick red fox jumps over the lazy dog"
204 chars
4 lines

In the above example, the regular expression /brown/g is used to replace all occurrences of the substring "brown" with the new substring "red".

gistlibby LogSnag