Replace characters globally Javascript
In JavaScript, the replace() method returns a new string with some or all matches of a pattern replaced by a replacement. The pattern can be a string or a RegExp, and the replacement can be a string or a function to be called for each match.
var str = "Color is Green and green is a cold color";
var result = str.replace(/green/gi, "blue");
console.log(result)
// -> Color is blue and blue is a cold color
Output
Color is blue and blue is a cold color
In this code example, the string "Color is Green and green is a cold color" is stored in the variable str. The replace() method is then used to replace all instances of the word "green" in the string with the word "blue". The result is then logged into the console.
Replace characters globally in Javascript
If you want to replace all occurrences of a particular character in a string, you can use the replace() method. This method takes two arguments: the character to be replaced, and the character to replace it with.
For example, the following code replaces first occurrences of "a" with "b":
var my_string = "aabcdaab";
my_string = my_string.replace("a", "b");
console.log(my_string);
// -> babcdaab
Replace all occurences if characters in a string
var my_str = "aabcdaab";
my_str = my_str.replace(/a/gi, "b");
console.log(my_str);
// -> bbbcdbbb
Replace characters globally - Case sensitive
- Replace multiple spaces between words with single space using javascript
- Convert all characters to lowercase using toLowerCase() method in javascript
- Calculate the frequency of characters in a string using Javascript
- Count the total number of characters in a textarea while typing in javascript
- Javascript to split string into array of characters
- Replace array values with another value Lodash
- Array.forEach() in javascript