Go Back   CodingForums.com > :: Client side development > JavaScript programming

Before you post, read our: Rules & Posting Guidelines

Reply
 
Thread Tools Rate Thread
Enjoy an ad free experience by logging in. Not a member yet? Register.
Old 12-07-2012, 12:54 PM   PM User | #1
BubikolRamios
Senior Coder

 
Join Date: Dec 2005
Location: Slovenia
Posts: 1,876
Thanks: 114
Thanked 76 Times in 76 Posts
BubikolRamios is on a distinguished road
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
BubikolRamios is offline   Reply With Quote
Old 12-07-2012, 01:49 PM   PM User | #2
WolfShade
Regular Coder

 
Join Date: Apr 2012
Location: St. Louis, MO, USA
Posts: 945
Thanks: 7
Thanked 97 Times in 97 Posts
WolfShade is an unknown quantity at this point
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".
WolfShade is offline   Reply With Quote
Old 12-07-2012, 02:14 PM   PM User | #3
007julien
Regular Coder

 
Join Date: May 2012
Location: France
Posts: 115
Thanks: 0
Thanked 17 Times in 15 Posts
007julien is an unknown quantity at this point
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..
007julien is offline   Reply With Quote
Old 12-07-2012, 03:09 PM   PM User | #4
Philip M
Supreme Master coder!

 
Philip M's Avatar
 
Join Date: Jun 2002
Location: London, England
Posts: 17,033
Thanks: 197
Thanked 2,410 Times in 2,388 Posts
Philip M has a spectacular aura aboutPhilip M has a spectacular aura aboutPhilip M has a spectacular aura about
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.
__________________

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.

Last edited by Philip M; 12-07-2012 at 04:30 PM.. Reason: Improved
Philip M is offline   Reply With Quote
Old 12-07-2012, 03:21 PM   PM User | #5
Philip M
Supreme Master coder!

 
Philip M's Avatar
 
Join Date: Jun 2002
Location: London, England
Posts: 17,033
Thanks: 197
Thanked 2,410 Times in 2,388 Posts
Philip M has a spectacular aura aboutPhilip M has a spectacular aura aboutPhilip M has a spectacular aura about
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.
Philip M is offline   Reply With Quote
Old 12-07-2012, 11:06 PM   PM User | #6
Old Pedant
Supreme Master coder!

 
Old Pedant's Avatar
 
Join Date: Feb 2009
Posts: 23,187
Thanks: 59
Thanked 3,995 Times in 3,964 Posts
Old Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to all
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.
Old Pedant is offline   Reply With Quote
Old 12-08-2012, 07:42 AM   PM User | #7
Philip M
Supreme Master coder!

 
Philip M's Avatar
 
Join Date: Jun 2002
Location: London, England
Posts: 17,033
Thanks: 197
Thanked 2,410 Times in 2,388 Posts
Philip M has a spectacular aura aboutPhilip M has a spectacular aura aboutPhilip M has a spectacular aura about
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.
Philip M is offline   Reply With Quote
Old 12-08-2012, 08:58 AM   PM User | #8
rdspoons
New Coder

 
Join Date: Jun 2009
Posts: 81
Thanks: 0
Thanked 8 Times in 8 Posts
rdspoons is on a distinguished road
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")
	})()
);
rdspoons is offline   Reply With Quote
Users who have thanked rdspoons for this post:
Philip M (12-08-2012)
Old 12-08-2012, 09:10 AM   PM User | #9
Philip M
Supreme Master coder!

 
Philip M's Avatar
 
Join Date: Jun 2002
Location: London, England
Posts: 17,033
Thanks: 197
Thanked 2,410 Times in 2,388 Posts
Philip M has a spectacular aura aboutPhilip M has a spectacular aura aboutPhilip M has a spectacular aura about
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.
__________________

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.

Last edited by Philip M; 12-08-2012 at 09:23 AM..
Philip M is offline   Reply With Quote
Old 12-08-2012, 09:18 AM   PM User | #10
rdspoons
New Coder

 
Join Date: Jun 2009
Posts: 81
Thanks: 0
Thanked 8 Times in 8 Posts
rdspoons is on a distinguished road
Quote:
Aaaarrgghhh! eval() is evil!!! felgall will have kittens!
See comment by Phillip M:
http://www.codingforums.com/showthread.php?t=283765
rdspoons is offline   Reply With Quote
Old 12-08-2012, 09:31 AM   PM User | #11
Philip M
Supreme Master coder!

 
Philip M's Avatar
 
Join Date: Jun 2002
Location: London, England
Posts: 17,033
Thanks: 197
Thanked 2,410 Times in 2,388 Posts
Philip M has a spectacular aura aboutPhilip M has a spectacular aura aboutPhilip M has a spectacular aura about
Quote:
Originally Posted by rdspoons View Post

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.
Philip M is offline   Reply With Quote
Old 12-08-2012, 12:36 PM   PM User | #12
rdspoons
New Coder

 
Join Date: Jun 2009
Posts: 81
Thanks: 0
Thanked 8 Times in 8 Posts
rdspoons is on a distinguished road
Phillp M,

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

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.
rdspoons is offline   Reply With Quote
Old 12-08-2012, 01:03 PM   PM User | #13
007julien
Regular Coder

 
Join Date: May 2012
Location: France
Posts: 115
Thanks: 0
Thanked 17 Times in 15 Posts
007julien is an unknown quantity at this point
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"
007julien is offline   Reply With Quote
Old 12-08-2012, 01:07 PM   PM User | #14
Philip M
Supreme Master coder!

 
Philip M's Avatar
 
Join Date: Jun 2002
Location: London, England
Posts: 17,033
Thanks: 197
Thanked 2,410 Times in 2,388 Posts
Philip M has a spectacular aura aboutPhilip M has a spectacular aura aboutPhilip M has a spectacular aura about
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/showthread.php?p=1298212
__________________

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.
Philip M is offline   Reply With Quote
Old 12-08-2012, 05:49 PM   PM User | #15
rdspoons
New Coder

 
Join Date: Jun 2009
Posts: 81
Thanks: 0
Thanked 8 Times in 8 Posts
rdspoons is on a distinguished road
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))
);
rdspoons is offline   Reply With Quote
Reply

Bookmarks

Jump To Top of Thread


Thread Tools
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump


All times are GMT +1. The time now is 06:11 AM.


Advertisement
Log in to turn off these ads.