PDA

View Full Version : regex problem. passing dynamica var in regex



s_sameer
09-15-2005, 05:53 AM
Hi i am stuck with some regex problem.
can any one tell me how to pass variable in regex
as in followin code will work
--------
var objRegExp = /$/g;
v1=v1.replace(objRegExp,"");
--------
and it will remove $ form the var v1
but if i want to pass it using following way as in by another var how do i do it
-------
var objRegExp = /v1.charAt(i)/g;
v1=v1.replace(objRegExp,"");
-------
can any one help me

jscheuer1
09-16-2005, 04:02 AM
eval('var objRegExp = /'+v1.charAt(i)+'/g');

mwinter
09-18-2005, 01:47 PM
var objRegExp = /$/g;
v1=v1.replace(objRegExp,"");
--------
and it will remove $ form the var v1As it stands, that won't do anything as the regular expression will match any string (but nothing in particular within it). The dollar ($) symbol is an end-of-string assertion (or end-of-line with the m flag). You need to prefix it with a backslash to make it a literal dollar:

  /\$/g



eval('var objRegExp = /'+v1.charAt(i)+'/g');Good grief, no!

I can guarantee that anytime you think you need to use the eval function, you're missing a much simpler, quicker, better alternative. In this case, the OP should use the RegExp constructor function. In its simplest form, this takes two arguments: the pattern and optional flags (both are strings). The previous object could be constructed with:


new RegExp('\\$', 'g')Note that because I'm using a string literal, the backslash that escapes the dollar symbol needs to be escaped itself (this would be true with eval as well). So, for the OP, we'd have:


new RegExp('\\' + v1.charAt(i), 'g')or in full:


v1 = v1.replace(new RegExp('\\' + v1.charAt(i), 'g'), '')Hope that helps,

Mike

jscheuer1
09-18-2005, 03:29 PM
v1 = v1.replace(new RegExp('\\' + v1.charAt(i), 'g'), '')Can't you use the two types of quotes to simplify that?

mwinter
09-18-2005, 05:01 PM
v1 = v1.replace(new RegExp('\\' + v1.charAt(i), 'g'), '')Can't you use the two types of quotes to simplify that?I'm not sure what you mean. The backslashes aren't there to escape the apostrophes, but to create a literal backslash. The other two string literals are separate.

When concatenated to the result of the charAt call, the literal backslash acts as an escape to make sure that the character isn't misinterpreted as an expression token.

However, I've just thought that this is more complicated than the solution I've proposed as other characters, when combined with a backslash, take on a different meaning.

To the OP: what does (or can) the string v1 contain?

Mike