...

View Full Version : regex variable



BubikolRamios
12-07-2012, 01:54 PM
s.replace(/something/gi,"");


How to proper insert variable in upper code instead of fixed string 'something' ?

WolfShade
12-07-2012, 02:49 PM
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.

007julien
12-07-2012, 03:14 PM
Use the constructor RegExp with something like this


var something = "foobar";
var rgx = new RegExp(something,"gi");

You need to escape the 11 following characters (often called "metacharacters") with a backslash :

the opening square bracket [,
the backslash \,
the caret ^,
the dollar sign $,
the period or dot .,
the vertical bar or pipe symbol |,
the question mark ?,
the asterisk or star *,
the plus sign +,
the opening round bracket (
and the closing round bracket ).
Then the script is a little more complicated (if the string contains metacharacters)

<script type="text/javascript">
var something="3+5=4";
var strForRegExp=something.replace(/(\[|\\|\^|\$|\.|\||\?|\*|\+|\(|\))/g,"\\$1");
// alert(strForRegExp);
var rgx=new RegExp(strForRegExp,'g');
var rsp=" foo 3+5=4 bar".replace(rgx,'');
alert(rsp)
</script>

Philip M
12-07-2012, 04:09 PM
<html>
<head>

<script type="text/javascript">

// REPLACE VARIABLE VALUE IN TEXTBOX OR TEXTAREA OR DIV BY ANOTHER VARIABLE VALUE

function doRep(IDS, val2replace, change2, elem) {
if (elem == "T") {
var txt = document.getElementById(IDS).value; // string to be analysed
}
if (elem == "D") {
var txt = document.getElementById(IDS).innerHTML; // string to be analyzed
}
var match = new RegExp(val2replace, 'gi'); // setting regex with val2replace global and case insensitive
var output = txt.replace(match, change2); // replacing variable string with variable replacement value
if (elem == "T") {
document.getElementById(IDS).value=output;
}
if (elem == "D") {
document.getElementById(IDS).innerHTML=output;
}
}
</script>

</head>

<body>

<input type = "text" id = "txt1" value = "Now is the time for all good men to come to the aid of their country." size = "70">
<br><br>
<textarea id="txt2" cols="40" rows="5">
Now is the time for all good men
to come to the aid of their country.
</textarea>
<br><br>
<div id="divText">
Now is the time for all good men<br>
to come to the aid of their country.
</div>
<br>
Find: <input type="text" id="txt2find" value=""><br>
Replace: <input type="text" id="reptext" value=""><br>
<br><br>
<button
onclick="doRep('txt1',document.getElementById('txt2find').value,document.getElementById('reptext').value, 'T')">
Textbox: Do it</button>
<button
onclick="doRep('txt2',document.getElementById('txt2find').value,document.getElementById('reptext').value, 'T')">
Textarea: Do it</button>
<button
onclick="doRep('divText',document.getElementById('txt2find').value,document.getElementById('reptext').value, 'D')">
DIV: Do it</button>


</body>
</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.

Philip M
12-07-2012, 04:21 PM
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.

How is that different from / better than


var txt = "Here is something and something and something";
txt = txt.replace(/(\s)?something/gi,"");

Old Pedant
12-08-2012, 12:06 AM
Please do note that if you use the RegExp contructor you must escape the \ characters that are used in the regular expression escapes.

So:


s.replace(/a\sb/gi,""); // replace all "a b" or "A B" or even "a\tB" with nothing

var re = new RegExp( "a\\sb", "gi" );
s.replace( re, "" );

See the \\s in the constructor version?

Philip M
12-08-2012, 08:42 AM
Please do note that if you use the RegExp contructor you must escape the \ characters that are used in the regular expression escapes.

So:


s.replace(/a\sb/gi,""); // replace all "a b" or "A B" or even "a\tB" with nothing

var re = new RegExp( "a\\sb", "gi" );
s.replace( re, "" );

See the \\s in the constructor version?

That is a little misleading. Should be


s = s.replace(/a\sb/gi,""); // replace all "a b" or "A B" or even "a\tB" with nothing
var re = new RegExp( "a\\sb", "gi" );
s = s.replace( re, "" );

rdspoons
12-08-2012, 09:58 AM
For what it's worth, you can also use eval to use variables in replace.


string.replace(eval("/"+somevar+"/gi"),"replacementString")



alert(
(function(){
var rvar = " simple";
return "This is a simple example with a simple string".replace(eval("/"+rvar+"/gi"),"n evaled")
})()
);

Philip M
12-08-2012, 10:10 AM
For what it's worth, you can also use eval to use variables in replace.


string.replace(eval("/"+somevar+"/gi"),"replacementString")



alert(
(function(){
var rvar = " simple";
return "This is a simple example with a simple string".replace(eval("/"+rvar+"/gi"),"n evaled")
})()
);


Aaaarrgghhh! eval() is evil!!! felgall will have kittens!

And replacementString is a literal, not a variable.

rdspoons
12-08-2012, 10:18 AM
Aaaarrgghhh! eval() is evil!!! felgall will have kittens!

See comment by Phillip M:
http://www.codingforums.com/showthread.php?t=283765

Philip M
12-08-2012, 10:31 AM
See comment by Phillip M:
http://www.codingforums.com/showthread.php?t=283765


Touche! But I said that felgall would have kittens, not that I would have kittens. :D
I thanked you for the post!

rdspoons
12-08-2012, 01:36 PM
Phillp M,

sorry, my attempt at humor did not show through - should have used a :D.


string.replace(eval("/"+somevar+"/gi"),"replacementString")


And replacementString is a literal, not a variable.

Yes, replacementString is a literal. somvar is the variable.

Again, thanks for the feedback.

007julien
12-08-2012, 02:03 PM
After a few tests the \ should be treated separately.
The following method may be helpful


<script type="text/javascript">
String.prototype.toRegExp=function(){return this.replace(/\\/g,'\\\\').replace(/(\[|\^|\$|\.|\||\?|\*|\+|\(|\))/g,'\\$1')}

//Example of use with all the «meta»characters
var something="[\\^$.|?*+()";// the \ is to escape in this string.

alert(("foo"+something+"bar").replace(new RegExp(something.toRegExp(),'g'),'')); //=>"foobar"

Philip M
12-08-2012, 02:07 PM
After a few tests the \ should be treated separately.
The following method may be helpful


<script type="text/javascript">
String.prototype.toRegExp=function(){return this.replace(/\\/g,'\\\\').replace(/(\[|\^|\$|\.|\||\?|\*|\+|\(|\))/g,'\\$1')}

//Example of use with all the «meta»characters
var something="[\\^$.|?*+()";// the \ is to escape in this string.

alert(("foo"+something+"bar").replace(new RegExp(something.toRegExp(),'g'),'')); //=>"foobar"

rnd me beat you to the draw! :)

http://www.codingforums.com/showthread.php?p=1298212

rdspoons
12-08-2012, 06:49 PM
Here is one way to allow variables in both the source regexp string and also the replacement string - using the evil eval :D.



alert(
// String replace with variable source regexp and variable replacement string via eval.
"visible global variable values:"+
(var1 = " simple") + " " +
(var2 = "n evaled") + " " +
(var3=[" little"," small", " tiny"]) + " " +
(i=0) + " " + (cnt=0)

+ // (1)
"\n\nThis is a simple example with a simple string" +
"\nThis is a simple example with a simple string".replace(eval("/"+var1+"/gi"),var2)+" "

+ // -OR- (2)
"\n\nThis is a simple example with a very simple really simple simple simple and I mean simple string"+
"\nThis is a simple example with a very simple really simple simple simple and I mean simple string".replace(eval("/"+var1+"/gi"),
function(n){
return i++%2?var3[cnt++]:n; //replace every other value
})

+ // -OR- (3)
"\n\nThis is a simple example with a simple string"+
"\nThis is a simple example with a simple string".replace(eval("/"+var1+"/gi"),
(function(m){
var i=0;
var a=function(n){
return m[i++];
};
return function(n){return a(n)}
})(var3))
);

Old Pedant
12-08-2012, 09:45 PM
It's not clear at all to me what your reason for using eval( ) is.

Is it simply so you can do it all in one line?

Not a good reason.

What's the difference between:


replace(eval("/"+var1+"/gi"), anything)

and


replace( (new RegExp( var1, "gi" ) ), anything )

???
Surely the second version is much more efficient, by avoiding the eval( ).

Even if eval( ) isn't evil, it's certainly less efficient than most anything else. (Especially in MSIE, unsurprisingly.)

rdspoons
12-09-2012, 12:02 AM
Old Pendant,

I've evaluated your comment and of course you're right. Thank you. I do fall back to eval when I believe it's required, but in the examples posted here I used eval because its a legal (if unwelcome) option that provided a solution. There is no doubt that replace((new RegExp(var1,"gi")),var2) is superior and more desirable, and as such, I stand corrected - in my evaluations.:o

Old Pedant
12-09-2012, 12:11 AM
I'd be really interested to see a situation where eval() is *REQUIRED*.

Other than parsing JSON that is returned by an AJAX call or something very similar.

I have yet to find a case where it is required, except when processing external JS data input.

007julien
12-09-2012, 02:38 PM
I forgott the / which is also to escape with javascript !


String.prototype.toRegExp=function(){return this.replace(/\\/g,'\\\\').replace(/(\[|\^|\$|\.|\||\?|\*|\+|\(|\)|\/)/g,'\\$1')}

//Example of use with all the «meta»characters
var something="[\\^$.|?*+()/"; // the slashe is to escape

alert(("foo"+something+"bar").replace(new RegExp(something.toRegExp(),'g'),''));// =>'foobar'



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum