Web Hosting Talk







View Full Version : JavaScript replace


sasha
07-27-2006, 07:25 PM
Hello I am looking for JavaScript equivalent of this:


$this->TokenSymbol = '%';
$this->ItemTokens = array ('TEST' => 'some value' , 'TEST2'=>'some other value' ) ;
$inString = 'This is some %NOT_USED% , %TEST% la la 'TEST2' ;

$outString = preg_replace ("/".$this->TokenSymbol."(\w+)".$this->TokenSymbol."/e" , "\$this->ItemTokens['\\1']" , $inString ) ;

echo $outString ;



$inString could be very large variable and this could be executed many times in the same page so it should be very efficient (entire input should be parsed in single pass)

Any help/pointers are welcome

tobiasly
07-28-2006, 02:33 PM
You need to use the JavaScript 1.5 specific string.replace() function which allows a function reference as its second parameter (known as "lambda function" or "callback").

I'm not sure which browsers allow JavaScript 1.5. To my knowledge Firefox 1.5+ and IE6+ do but I don't know about others. There is a JavaScript library "JSL" which claims to modify older browsers to allow this type of string.replace() but I have not used it:
http://www.devpro.it/JSL/

Anyway, here is a page that tests this:

<html>
<head>
<script>

var tokens = new Array();
tokens['TEST'] = 'some value';
tokens['TEST2'] = 'some other value';

function doreplace(str) {
str = str.replace(/%(\w+)%/g, lookup );
alert(str);
}

function lookup(match, r1) {
var rep = tokens[r1];

if(rep == null)
return match;
else
return rep;
}

</script>
</head>

<body>
<button onclick="doreplace('This is some %NOT_USED% ,%TEST% la la %TEST2%')">click here to test</button>
</body>
</html>
In this case the string.replace() function is passed the matched string, followed by the backreferenced matches. Note that in the str.replace() function, "lookup" does not have parentheses after it: this causes a reference to the "lookup" function to be passed without actually calling the function. Then the replace() function itself calls the function while passing it the correct values.

More info on the JavaScript 1.5 version of string.replace() can be found here:
http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference:Global_Objects:String:replace