String.replace() Introduction
Syntax:
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()
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
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
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
var text = '"JavaScript" Very powerful! ';
text.replace(/"([^"]*)"/g, "[$1]");
// Returns: [JavaScript] Very powerful!
String.replace( ) Capitalize the first letter of all characters
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.