![]() |
regex variable
Code:
s.replace(/something/gi,""); |
I don't think you can use a variable in regex.
One thing I did notice, however, is that if you're trying to replace more than just one instance of something, you can split on something, then join on "". s.split(something); s.join(""); This will replace all instances of variable something with "". If you have two or more spaces in the resulting string, then use regex to replace all double-or-more instances of space with just single space. |
Use the constructor RegExp with something like this
Code:
var something = "foobar";
Code:
<script type="text/javascript"> |
Code:
<html>The 11 meta-characters mentioned by julien007 must be escaped in the "to find" string but not of course in the "replace by" string. |
Quote:
Code:
var txt = "Here is something and something and something"; |
Please do note that if you use the RegExp contructor you must escape the \ characters that are used in the regular expression escapes.
So: Code:
s.replace(/a\sb/gi,""); // replace all "a b" or "A B" or even "a\tB" with nothing |
Quote:
Code:
s = s.replace(/a\sb/gi,""); // replace all "a b" or "A B" or even "a\tB" with nothing |
For what it's worth, you can also use eval to use variables in replace.
string.replace(eval("/"+somevar+"/gi"),"replacementString")Code:
alert( |
Quote:
And replacementString is a literal, not a variable. |
Quote:
http://www.codingforums.com/showthread.php?t=283765 |
Quote:
Touche! But I said that felgall would have kittens, not that I would have kittens. :D I thanked you for the post! |
Phillp M,
sorry, my attempt at humor did not show through - should have used a :D. Quote:
Quote:
Again, thanks for the feedback. |
After a few tests the \ should be treated separately.
The following method may be helpful Code:
<script type="text/javascript"> |
Quote:
http://www.codingforums.com/showthread.php?p=1298212 |
Here is one way to allow variables in both the source regexp string and also the replacement string - using the evil eval :D.
Code:
alert( |
| All times are GMT +1. The time now is 01:32 PM. |
Powered by vBulletin®
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.