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.tsx133 chars5 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.tsx191 chars5 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.tsx185 chars5 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