kael.shipman Posted July 11, 2007 Share Posted July 11, 2007 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 Quote Link to comment Share on other sites More sharing options...
kael.shipman Posted July 11, 2007 Author Share Posted July 11, 2007 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> Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.