javascript - How do you use a variable in a regular expression? -
i create string.replaceall() method in javascript , i'm thinking using regex terse way it. however, can't figure out how pass variable in regex. can replace instances of "b" "a".
"ababab".replace(/b/g, "a");
but want this:
string.prototype.replaceall = function(replacethis, withthis) { this.replace(/replacethis/g, withthis); };
but replace text "replacethis"...so how pass variable in regex string?
instead of using /regex/g
syntax, can construct new regexp object:
var replace = "regex"; var re = new regexp(replace,"g");
you can dynamically create regex objects way. do:
"mystring".replace(re, "newstring");
Comments
Post a Comment