replace string in javascript

To replace all occurrences of a substring in a string in JavaScript, we can use the replace() method which can take a string or a regular expression as the first argument.

Here is an example of using the replace() method to replace all occurrences of a given substring with a new string:

index.tsx
let originalString = "Hello, World!";
let newString = originalString.replace("Hello", "Hi");

// newString now contains "Hi, World!"
133 chars
5 lines

In the example above, we are replacing the substring "Hello" with "Hi" in the original string. The replace() function returns a new string with the replacements made.

We can also use regular expressions to replace substrings in a more flexible way. Here is an example of using a regular expression to replace all occurrences of a given substring with a new string:

index.tsx
let originalString = "The quick brown fox jumps over the lazy dog";
let newString = originalString.replace(/the/gi, "a");

// newString now contains "a quick brown fox jumps over a lazy dog"
191 chars
5 lines

In the example above, we are replacing all occurrences of the substring "the" (ignoring case) with the character "a" using the global and case-insensitive regular expression /the/gi.

Another way to replace substrings in JavaScript is to use the substr() method. This method allows us to replace a substring at a specific index with a new string. Here is an example:

index.tsx
let originalString = "Hello, World!";
let newString = originalString.substr(0, 5) + "there" + originalString.substr(5 + "Hello".length);

// newString now contains "Hellothere, World!"
185 chars
5 lines

In the example above, we are replacing the substring "Hello" with "there" using the substr() method to replace the characters at specific indices in the string.

Overall, the replace(), regular expressions, and substr() functions provide us with different options for replacing substrings in JavaScript.

gistlibby LogSnag