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
https://forums.phpfreaks.com/topic/59386-solved-variables-in-a-regular-expression/
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>

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.