Home >Web Front-end >JS Tutorial >About JS string function String.replace()_Basic knowledge

About JS string function String.replace()_Basic knowledge

WBOY
WBOYOriginal
2016-05-16 17:38:14983browse

Replace the substring(s) matching the given regular expression

string.replace(regexp, replacement)

Parameters:

regexp: RegExp object or string

replacement: A string of replacement text, or a function used to generate the corresponding replacement text when called.

Return:

Returns a replaced new string

Description:

replacement can be a string or a function. If it is a function, it will be called on each match and the string it returns will be used as the replacement text.

Parameters passed into the function:

1) String matching the pattern

2) A string matching a certain parenthesis subexpression in the pattern, which may be 0 or more such parameters

3) Integer, specifying the position in String where the matching result appears

4) string itself

Example:

Copy code The code is as follows:

//Make sure the case of the word "javascript" is correct
text.replace(/javascript/i, 'JavaScript');
//Replace all double quotes with pairs of leading and trailing single quotes
text.replace(/"([^"])" /g, "''$1''");
//Convert a single name from the format "Mack, Xu" to "Xu Mack"
name.replace(/(w )s*,s *(w )/, "$2 $1");
//Capitalize the first letters of all words in a string
text.replace(/bw b/g, function(word) {
return word.substring(0, 1).toUpperCase() word.substring(1);
});
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn