JS globally replaces the specified characters in the string
The replace() method in JavaScript is used to replace a string or a substring in it with a specified character, or to replace a substring that matches a regular expression.This method does not change the original string。
grammar
(regexp/substr, replacement)
It will look for substrings matching regexp in stringObject and replace those substrings with replacement. If regexp has the global flag g, the replace() method replaces all matching substrings. Otherwise, it only replaces the first matching substring. Definition quoted from http:///jsref/jsref_replace.asp
As above, the requirement for global string replacement can be implemented using a regular expression with the global flag g:
// Replace a in str with Avar str = 'abcabcabc'; var result = ('a', 'A'); ('result:' + result); // Output result:Abcabcabc// Replace all a in str with Avar str = 'abcabcabc'; var result = (/a/g, 'A'); ('result:' + result); // Output result:AbcAbcAbc
Note: When using regular expression parameters, you do not need to be enclosed in quotes, otherwise it will be processed as a string.
refer to:JavaScript replace() method
Replace characters in strings in Js
First, mainly use the replace method to replace characters
Using the replace method alone can only replace the first one of the repeated characters in the string.
var str = 'Come on koalas'; alert(('Oil','meal')); // Output result: Koalas add rice oil var str = 'abcoefoxyozzopp';
Only the first word oil in the code has become rice.
2. Use for loop and replace to replace all characters in the string.
var str = 'Come on koalas on koalas'; for(var i = 0; i < ; i++){ if (str[i] == 'Oil') { str = ('Oil','meal'); // Note that after replacement, it becomes a new array } } alert(str); // Output result Add rice to koalas and rice
You can also use while loop.
This is the article about JS's global replacement of specified characters in strings. For more relevant contents for JS' global replacement of specified characters, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!