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

Popular posts from this blog

Magento/PHP - Get phones on all members in a customer group -

php - .htaccess mod_rewrite for dynamic url which has domain names -

Website Login Issue developed in magento -