JS Replace Method


JS replace() method can substitute a substring of a string, and return the new string. It supports regular expression.

var s = "perschon.com R language tutorial";
var x = s.replace("R language","javascript");
//x is "perschon.com javascript tutorial"
//s is "perschon.com R language tutorial"


Using regular expression:

var x = s.replace(/\sR.+ge\s/,"javascript");
//same result


It only replace the first occurrence by default:

var s = "perschon.com R language tutorial";
var x = s.replace("m","M");
//x is "endMemo.com R language tutorial"


Using the "g" modifier for global replacement:

var s = "perschon.com R language tutorial";
var x = s.replace(/m/g,"M");
//x is "endMeMo.coM R language tutorial"


Using the "i" modifier for case insensitive replacement:

var s = "perschon.com R language tutorial";
var x = s.replace(/r/gi,"999");
//x is "perschon.com 999 language tuto999ial"


Using $0, $1, $2 ... to replace the matches in brackets:

var s = "perschon.com R language tutorial";
var x = s.replace(/\sR(.+ge)\s/," javascript$1 ");
//perschon.com javascript language tutorial
//$0 is the whole match of the pattern
var x2 = s.replace(/\sR(.+ge)\s/,"javascript$0");
//perschon.com javascript R language tutorial


Use variables in string replace:

var str = "perschon.com";
var pat= new RegExp("me","g");
var str2 = str.replace(pat,"");
alert(str2); //endmo.com


For more javascript string functions, please click here.
For more javascript regular expression usage, please click here.

convert.idontcarewhatyouthink.net © 2021  Terms of Use | Home