Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Page 1 of 2 12 LastLast
Results 1 to 15 of 19

Thread: regex variable

  1. #1
    Senior Coder
    Join Date
    Dec 2005
    Location
    Slovenia
    Posts
    1,960
    Thanks
    120
    Thanked 76 Times in 76 Posts

    regex variable

    Code:
    s.replace(/something/gi,"");
    How to proper insert variable in upper code instead of fixed string 'something' ?
    Found a flower or bug and don't know what it is ?
    agrozoo.net galery
    if you don't spot search button at once, there is search form:
    agrozoo.net galery search

  • #2
    Regular Coder
    Join Date
    Apr 2012
    Location
    St. Louis, MO
    Posts
    985
    Thanks
    7
    Thanked 101 Times in 101 Posts
    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.
    ^_^

    If anyone knows of a website that can offer ColdFusion help that isn't controlled by neurotic, pedantic jerks* (stackoverflow.com), please PM me with a link.
    *
    The neurotic, pedantic jerks are not the owners; just the people who are in control of the "popularity contest".

  • #3
    Regular Coder
    Join Date
    May 2012
    Location
    France
    Posts
    224
    Thanks
    0
    Thanked 32 Times in 30 Posts
    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>
    Last edited by 007julien; 12-07-2012 at 02:17 PM.

  • #4
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    17,910
    Thanks
    203
    Thanked 2,531 Times in 2,509 Posts
    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.
    Last edited by Philip M; 12-07-2012 at 04:30 PM. Reason: Improved

    All the code given in this post has been tested and is intended to address the question asked.
    Unless stated otherwise it is not just a demonstration.

  • #5
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    17,910
    Thanks
    203
    Thanked 2,531 Times in 2,509 Posts
    Quote Originally Posted by WolfShade View Post
    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,"");

    All the code given in this post has been tested and is intended to address the question asked.
    Unless stated otherwise it is not just a demonstration.

  • #6
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,155
    Thanks
    75
    Thanked 4,338 Times in 4,304 Posts
    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?
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • #7
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    17,910
    Thanks
    203
    Thanked 2,531 Times in 2,509 Posts
    Quote Originally Posted by Old Pedant View Post
    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, "" );

    All the code given in this post has been tested and is intended to address the question asked.
    Unless stated otherwise it is not just a demonstration.

  • #8
    New Coder
    Join Date
    Jun 2009
    Posts
    81
    Thanks
    0
    Thanked 8 Times in 8 Posts
    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")
    	})()
    );

  • Users who have thanked rdspoons for this post:

    Philip M (12-08-2012)

  • #9
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    17,910
    Thanks
    203
    Thanked 2,531 Times in 2,509 Posts
    Quote Originally Posted by rdspoons View Post
    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.
    Last edited by Philip M; 12-08-2012 at 09:23 AM.

    All the code given in this post has been tested and is intended to address the question asked.
    Unless stated otherwise it is not just a demonstration.

  • #10
    New Coder
    Join Date
    Jun 2009
    Posts
    81
    Thanks
    0
    Thanked 8 Times in 8 Posts
    Aaaarrgghhh! eval() is evil!!! felgall will have kittens!
    See comment by Phillip M:
    Javascript Coding Problem

  • #11
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    17,910
    Thanks
    203
    Thanked 2,531 Times in 2,509 Posts
    Quote Originally Posted by rdspoons View Post
    See comment by Phillip M:
    Javascript Coding Problem

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

    All the code given in this post has been tested and is intended to address the question asked.
    Unless stated otherwise it is not just a demonstration.

  • #12
    New Coder
    Join Date
    Jun 2009
    Posts
    81
    Thanks
    0
    Thanked 8 Times in 8 Posts
    Phillp M,

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

    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.

  • #13
    Regular Coder
    Join Date
    May 2012
    Location
    France
    Posts
    224
    Thanks
    0
    Thanked 32 Times in 30 Posts
    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"

  • #14
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    17,910
    Thanks
    203
    Thanked 2,531 Times in 2,509 Posts
    Quote Originally Posted by 007julien View Post
    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/post-javascript/283755-replace-variable-value-textbox-textarea-div-another-value.html#post1298212

    All the code given in this post has been tested and is intended to address the question asked.
    Unless stated otherwise it is not just a demonstration.

  • #15
    New Coder
    Join Date
    Jun 2009
    Posts
    81
    Thanks
    0
    Thanked 8 Times in 8 Posts
    Here is one way to allow variables in both the source regexp string and also the replacement string - using the evil eval .

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


  •  
    Page 1 of 2 12 LastLast

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •