JS Replace Method


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

var s = "endmemo.com R language tutorial";
var x = s.replace("R language","javascript");
//x is "endmemo.com javascript tutorial"
//s is "endmemo.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 = "endmemo.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 = "endmemo.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 = "endmemo.com R language tutorial";
var x = s.replace(/r/gi,"999");
//x is "endmemo.com 999 language tuto999ial"


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

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


Use variables in string replace:

var str = "endmemo.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.

endmemo.com © 2020  Terms of Use | Home