Thread: regex variable
View Single Post
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