replace (String - JavaScript)
Replaces a substring.
Defined in
String (Standard - JavaScript)Syntax
replace(searchValue:string, replaceValue:string) : string
Parameters | Description |
---|---|
searchValue |
The substring to be replaced. |
replaceValue |
The replacement substring. |
Return value | Description |
---|---|
string |
The string with the replacement made. |
Usage
If the string does not contain the substring to be replaced, the return value is the original string.If the first parameter is a string, this method replaces the first string that matches exactly. If the first parameter is a regular expression, this method replaces all strings that match according to the syntax of the regular expression.
Examples
(1) This example returnsParis---Moscow
Tokyo
.var cities = new String("Paris Moscow Tokyo");
cities.replace(" ", "---")
(2) This example returns
Paris---Moscow---Tokyo
.var cities = new String("Paris Moscow Tokyo");
var cities2 = cities.replace(" ", "---");
while (! cities.equals(cities2)) {
cities = cities2;
cities2 = cities.replace(" ", "---");
}
cities
(3) This example also returns
Paris---Moscow---Tokyo
using
a regular expression rather than JavaScript iteration.var cities = new String("Paris Moscow Tokyo");
cities.replace(/( )/g, "---")