Home > Web Front-end > JS Tutorial > body text

The wonderful use of Javascript String.replace_Basic knowledge

WBOY
Release: 2016-05-16 18:47:04
Original
1024 people have browsed it

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.
Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template