Home  >  Article  >  Web Front-end  >  The wonderful use of Javascript String.replace_Basic knowledge

The wonderful use of Javascript String.replace_Basic knowledge

WBOY
WBOYOriginal
2016-05-16 18:47:041010browse

String.replace() Introduction
Syntax:

Copy code The code is as follows:

string .replace(regexp, replacement)

regexp: the regular expression you want to perform the replacement operation. If a string is passed in, it will be treated as an ordinary character and will only Perform a replacement operation; if it is a regular expression with the global (g) modifier, all occurrences of the target character will be replaced, otherwise, only one replacement operation will be performed.
replacement: The character you want to replace with.
The return value is the string after performing the replacement operation.
Simple usage of String.replace()
Copy code The code is as follows:

var text = "javascript is very powerful!";
text.replace(/javascript/i, "JavaScript");
// Returns: JavaScript is very powerful!

String.replace( ) replaces all occurrences of the target character
Copy code 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() implements swapping positions
Copy code The code is as follows:

var name= "Doe, John";
name.replace(/(w )s*,s*(w )/, "$2 $1");
// Return: John Doe

String.replace( ) implements the replacement of all characters contained in double quotes with characters contained in square brackets
Copy code The code is as follows:

var text = '"JavaScript" Very powerful! ';
text.replace(/"([^"]*)"/g, "[$1]");
// Returns: [JavaScript] Very powerful!

String.replace( ) Capitalize the first letter of all characters
Copy code The code is as follows:

var text = 'a journey of a thousand miles begins with single step.';
text.replace(/bw b/g, function(word) {
return word.substring(0,1).toUpperCase( )
word.substring(1);
});
// Return: A Journey Of A Thousand Miles Begins With Single Step.
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