Jump to content

[SOLVED] Variables in a Regular Expression


kael.shipman

Recommended Posts

Hey,

 

Does anyone know how I can include variables in a replace() method? Alternatively, I could use a way to specify a global replace when using a string as the expression. Here's what's happening:

 

<script type="text/javascript">
var a = "2";
var str = "This here is my string #2, and it sure is serving my #2 purpose well.";
alert(str.replace("#"+a,"Number Two")); //This needs to replace globally
</script>

 

Again, I need either to be able to specify that the method is to replace EACH occurrence of the string OR I need to be able to insert the "a" variable into a regular expression (which can of course accomplish the same goal with the "g" flag).

 

Thanks,

kael

Link to comment
Share on other sites

Nevermind; found it!

 

I didn't know about the RegExp Object. For those of you who found this post and are wondering about the solution, here it is:

 

<script type="text/javascript">
var a = "2";
var str = "This here is my string #2, and it sure is serving my #2 purpose well.";
var b = new RegExp("#"+a,"g"); //forces variable "b" to be a regular expression and adds the "global" flag to it
alert(str.replace(b,"Number Two"));
</script>

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.