CodingForums.com

CodingForums.com (http://www.codingforums.com/index.php)
-   JavaScript programming (http://www.codingforums.com/forumdisplay.php?f=2)
-   -   regex variable (http://www.codingforums.com/showthread.php?t=283741)

BubikolRamios 12-07-2012 12:54 PM

regex variable
 
Code:

s.replace(/something/gi,"");
How to proper insert variable in upper code instead of fixed string 'something' ?

WolfShade 12-07-2012 01: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 02:14 PM

Use the constructor RegExp with something like this
Code:

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

You need to escape the 11 following characters (often called "metacharacters") with a backslash :
  1. the opening square bracket [,
  2. the backslash \,
  3. the caret ^,
  4. the dollar sign $,
  5. the period or dot .,
  6. the vertical bar or pipe symbol |,
  7. the question mark ?,
  8. the asterisk or star *,
  9. the plus sign +,
  10. the opening round bracket (
  11. and the closing round bracket ).
Then the script is a little more complicated (if the string contains metacharacters)
Code:

<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 03:09 PM

Code:

<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 03:21 PM

Quote:

Originally Posted by WolfShade (Post 1298049)
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

Code:

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


Old Pedant 12-07-2012 11:06 PM

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

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

See the \\s in the constructor version?

Philip M 12-08-2012 07:42 AM

Quote:

Originally Posted by Old Pedant (Post 1298201)
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

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

See the \\s in the constructor version?

That is a little misleading. Should be

Code:

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 08:58 AM

For what it's worth, you can also use eval to use variables in replace.


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

Code:

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 09:10 AM

Quote:

Originally Posted by rdspoons (Post 1298283)
For what it's worth, you can also use eval to use variables in replace.


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

Code:

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 09:18 AM

Quote:

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 09:31 AM

Quote:

Originally Posted by rdspoons (Post 1298290)


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 12:36 PM

Phillp M,

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

Quote:

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

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 01:03 PM

After a few tests the \ should be treated separately.
The following method may be helpful
Code:

<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 01:07 PM

Quote:

Originally Posted by 007julien (Post 1298318)
After a few tests the \ should be treated separately.
The following method may be helpful
Code:

<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 05: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.

Code:

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))
);



All times are GMT +1. The time now is 01:32 PM.

Powered by vBulletin®
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.