How can I replace all occurrences of a string in JavaScript?Rashid D
To replace all occurrences of a string in JavaScript, you can use thereplace()
method in combination with regular expressions. Here's a step-by-step guide on how to achieve this:
1. Create a regular expression with the global flag (g) to match all occurrences of the string:
1 2 3 4
const searchStr = 'old'; const regex = new RegExp(searchStr, 'g');
2. Use thereplace()
method on the target string and pass the regular expression and the replacement string as arguments:
1 2 3 4 5 6
const targetStr = 'old old old'; const replacementStr = 'new'; const result = targetStr.replace(regex, replacementStr);
3. Thereplace()
method returns a new string with all occurrences of the search string replaced. Assign the result to a variable (result in the example) to capture the modified string.
In the given example, thereplace()
method will replace all occurrences of'old'
with'new'
in thetargetStr
string. The resulting value will be'new new new'
.
Note: If the search string contains any characters with special meaning in regular expressions (e.g.,$
,^
,*
), make sure to escape them usingRegExp.escape()
or by adding backslashes before them in the search string.
If you need to perform case-insensitive replacements, you can add thei
flag to the regular expression, like this:
1 2
const regex = new RegExp(searchStr, 'gi');
In this case, both uppercase and lowercase occurrences of the search string will be replaced.
By using thereplace()
method with a regular expression and the global flag, you can easily replace all occurrences of a string in JavaScript.
Similar Questions
How can I remove all occurrences of a specific element from an array in JavaScript?
How can I replace a specific value in an array in JavaScript?
How can I create a random string in JavaScript?
How can I split a string into an array in JavaScript?
How do I reverse a string in JavaScript?
How can I remove HTML tags from a string in JavaScript?
How can I convert an array to a lowercase string in JavaScript?
How do I remove whitespace from both ends of a string in JavaScript?
How can I convert an array to a string in JavaScript?
How can I validate a password strength in JavaScript?
How can I convert a function to a string in JavaScript?
How can I convert a function to a string in JavaScript?
How can I get the current timestamp in JavaScript?
How can I capitalize the first letter of a string in JavaScript?
How do I remove whitespace from a string in JavaScript?
How can I get the current URL in JavaScript?
How can I convert a blob to a base64 string in JavaScript?
How can I convert an object to a string in JavaScript?