-
Notifications
You must be signed in to change notification settings - Fork 0
JS String Prototype Replace
The replace()
method returns a new string with some or all matches of a pattern replaced by a replacement. The pattern can be a string or a RegExp
, and the replacement can be a string or a function to be called for each match.
str.replace(regexp|substr, newSubStr|function[, flags])
regexp (pattern)
A RegExp object. The match is replaced by the return value of parameter #2.
substr (pattern)
A String that is to be replaced by newSubStr.
newSubStr (replacement)
The String that replaces the substring received from parameter #1. A number of special replacement patterns are supported; see the "Specifying a string as a parameter" section below.
function (replacement)
A function to be invoked to create the new substring (to put in place of the substring received from parameter #1). The arguments supplied to this function are described in the "Specifying a function as a parameter" section below.
A new string with some or all matches of a pattern replaced by a replacement.
This method does not change the String object it is called on. It simply returns a new string.
To perform a global search and replace, either include the g switch in the regular expression or if the first parameter is a string, include g in the flags parameter.
var str = 'Twas the night before Xmas...';
var newstr = str.replace(/xmas/i, 'Christmas');
console.log(newstr); // Twas the night before Christmas...
function f2c(s1) {
// Initialize pattern.
var test = /(\d+(\.\d*)?)F\b/g;
// Use a function for the replacement.
var s2 = s1.replace(test,
function($0,$1,$2)
{
return((($1-32) * 5/9) + "C");
}
)
return s2;
}
document.write(f2c("Water freezes at 32F and boils at 212F."));
// Output: Water freezes at 0C and boils at 100C.
Learn to code and help nonprofits. Join our open source community in 15 seconds at http://freecodecamp.com
Follow our Medium blog
Follow Quincy on Quora
Follow us on Twitter
Like us on Facebook
And be sure to click the "Star" button in the upper right of this page.
New to Free Code Camp?
JS Concepts
JS Language Reference
- arguments
- Array.prototype.filter
- Array.prototype.indexOf
- Array.prototype.map
- Array.prototype.pop
- Array.prototype.push
- Array.prototype.shift
- Array.prototype.slice
- Array.prototype.some
- Array.prototype.toString
- Boolean
- for loop
- for..in loop
- for..of loop
- String.prototype.split
- String.prototype.toLowerCase
- String.prototype.toUpperCase
- undefined
Other Links