This article describes the JS String function String. replace (). For more information, see. Replace (one or more) substrings matching a given regular expression
String. replace (regexp, replacement)
Parameters:
Regexp: RegExp object or string
Replacement: replacement text string, or a function, used to generate the corresponding replacement text during the call.
Return Value:
Returns a new string.
Description:
Replacement can be a string or a function. If it is a function, it will be called on each matching result, and the string it returns will be used as the replacement text.
Parameters passed in the function:
1) string matching the pattern
2) match the string of A parentheses subexpression in this mode. It may be 0 or multiple such parameters.
3) an integer that specifies the position where the matching result appears in the String.
4) string itself
Example:
The Code is as follows:
// Make sure that the word "javascript" is in the correct case.
Text. replace (/javascript/I, 'javascript ');
// Replace all double quotation marks with the correct single quotation marks
Text. replace (/"([^"]) "/g," ''$1 ''");
// Convert a separate name from the format "Mack, Xu" to "Xu Mack"
Name. replace (/(\ w +) \ s *, \ s * (\ w +)/, "$2 $1 ");
// Capital the first letter of all words in a string
Text. replace (/\ B \ w + \ B/g, function (word ){
Return word. substring (0, 1). toUpperCase () + word. substring (1 );
});