Jump to content

Variables in Regular Expressions


jesh

Recommended Posts

Ok, I know with regular expressions, I can replace all instances of a string within another string like this:

var string = "http://www.microsoft.com is the best site out there!  Don't you just love Microsoft?";var newstring = string.replace(/microsoft/gi, "W3Schools");document.write(newstring);

That works great. Everywhere (case-insensitive, btw) where you see "microsoft", "W3Schools" now appears. My question is, what if the string that I want to replace is a variable?

var replaceWord = "microsoft";var string = "http://www.microsoft.com is the best site out there!  Don't you just love Microsoft?";// how can I use string.replace() here to replace all instances// of whatever the value is of replaceWord?

EDIT:========================================Ah...Google to the rescue again. doh!Searching Google for "variables in regular expressions" returned this:http://www.webreference.com/js/column5/methods.htmlThis code works for me:

var replaceWord = "microsoft";var string = "http://www.microsoft.com is the best site out there!  Don't you just love Microsoft?";var regex = new RegExp(replaceWord, "gi");var newstring = string.replace(regex, "W3Schools");document.write(newstring);

I tried Google first, but it wasn't until I wrote this post that I was able to word my searching correctly. I answered it myself, go figure! Maybe the post will help someone else at least. heh.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...