Document directory
Because the replaceall () method is not provided in Javascript, it is not very comfortable to use. Next I will show you how to use the replace method to obtain columns with other effects, such as the replaceall effect.
String. Replace ()
Syntax:
string.replace(regexp, replacement)
Regexp: the regular expression of the replacement operation. If a string is input, it is processed as a normal character and only one replacement operation is performed. If it is a regular expression, with the global (g) modifier, all target characters will be replaced. Otherwise, only one replacement operation will be performed.
Replacement: the character you want to replace.
The return value is the string after the replacement operation is executed.
String. Replace ()
VaR text = "javascript is very powerful! "; Text. Replace (/JavaScript/I," JavaScript "); // return: javascript is very powerful!
String. Replace () replace all Target Characters
VaR text = "javascript is very powerful! Javascript is my favorite language! "; Text. Replace (/JavaScript/ig," JavaScript "); // return: javascript is very powerful! Javascript is my favorite language!
In addition, we can also use this to achieve our results:
string.replace(new RegExp(oldString,"gm"),newString))
Enter:
javascript:alert("abcabcabc".replace(new RegExp("a","gm"),"ad"))
String. Replace ()
VaR name = "doe, John"; Name. replace (/(\ W +) \ s *, \ s * (\ W +)/, "$2 $1"); // return: John Doe
String. Replace () is used to replace all characters in double quotation marks with characters in brackets.
VaR text = '"JavaScript" is very powerful! '; Text. Replace (/"([^"] *) "/g," [$1] "); // return: [JavaScript] is very powerful!
String. Replace () uppercase letters
VaR text = 'a journey of a thousand miles begins with single step. '; text. replace (/\ B \ W + \ B/g, function (Word) {return word. substring (0, 1 ). touppercase () + word. substring (1) ;}); // return: A journey of a thousand miles begins with single step.