String.Replace () Introduction
Grammar:
Copy Code code as follows:
String.Replace (RegExp, replacement)
RegExp: The regular expression for which you want to perform the substitution operation. If a string is passed in, it is treated as a normal character, and only one substitution operation is performed, and if the regular expression is present with the global (g) modifier, all occurrences of the target character are replaced. Only one substitution operation will be performed.
Replacement: The character you want to replace.
The return value is the string after the substitution operation.
Simple usage of string.replace ()
Copy Code code as follows:
var text = "JavaScript is very powerful!" ";
Text.replace (/javascript/i, "JavaScript");
Back: JavaScript is very powerful!
String.Replace () Replaces all occurrences of the target character
Copy Code code as follows:
var text= "JavaScript is very powerful! JAVASCRIPT is one of my favorite languages! ";
Text.replace (/javascript/ig, "JavaScript");
Back: JavaScript is very powerful! JavaScript is one of my favorite languages!
String.Replace () to implement the swap position
Copy Code code as follows:
var name= "Doe, John";
Name.replace (/(\w+) \s*,\s* (\w+)/, "$ $");
Back: John Doe
String.Replace () implementation replaces all double quotes with characters enclosed in brackets
Copy Code code as follows:
The var text = ' JavaScript ' is very powerful! ';
Text.replace ([^ "]*)"/g, "[$]");
Back: [JavaScript] very powerful!
String.Replace () capitalize all characters first letter
Copy Code code 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.