Character replacement is a very important function. javascript has a String. replace (), but this method has many advantages that are not unknown to new users. If you use it well, you can save a lot of valuable time. What are you waiting? Come in now! String. replace ()
Syntax:
The Code is as follows:
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 ()
The Code is as follows:
Var text = "javascript is very powerful! ";
Text. replace (/javascript/I, "JavaScript ");
// Return: JavaScript is very powerful!
String. replace () replace all Target Characters
The Code is as follows:
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!
String. replace ()
The Code is as follows:
Var name = "Doe, John ";
Name. replace (/(\ w +) \ s *, \ s * (\ w +)/, "$2 $1 ");
// Return value: John Doe
String. replace () is used to replace all characters in double quotation marks with characters in brackets.
The Code is as follows:
Var text = '"JavaScript" is very powerful! ';
Text. replace (/"([^"] *) "/g," [$1] ");
// Return: [JavaScript] is very powerful!
String. replace () uppercase letters
The Code is as follows:
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.