VK wrote:
Michael wrote: In PHP there is a function called str_replace
(http://php.net/str_replace). Basically you can freed in two strings
and a "subject" string. Then it goes through the subject string
searching for occurences of the "search" string and replaces them with
the "replace" string. Is there something simular in JavaScript
[snip] There is not exact equivalent of srt_replace in JavaScript, but one can
make an exact equivalent of it using RegExp tools if it's needed.
[snip]
Here is a javascript version of PHP's str_replace. It uses the Array's
"map" and "forEach" methods so those will need to be added to the
prototype if necessary. Also, since Javascript passes numeric variables
by value instead of by reference the fourth argument is a callback
function that returns the replacement count.
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Javascript str_replace</title>
<script type="text/javascript">
function str_replace(search, replace, subject, countfn){
var replacement, temparr, rplcount=0;
var searchIsArray = (typeof search == 'object' &&
search.constructor == Array);
var replaceIsArray = (typeof replace == 'object' &&
replace.constructor == Array);
var subjectIsArray = (typeof subject == 'object' &&
subject.constructor == Array);
if (!searchIsArray) search = [search];
if (!subjectIsArray) subject = [subject];
var rval = subject.map(
function(sub){
search.forEach(
function(el, i){
if (replaceIsArray){
replacement = (i>replace.length-1)?'':replace[i];
}else{
replacement = replace;
}
temparr = sub.split(el);
rplcount += temparr.length - 1;
sub = temparr.join(replacement);
}
);
return sub;
}
);
if (countfn && typeof countfn == 'function') countfn(rplcount);
return subjectIsArray?rval:rval[0];
}
function init(){
var cnt=0, str='abc';
function cfn(x){cnt+=x}
alert(str_replace('b','x',str,cfn));
alert(str_replace(['a','c'],'x',str,cfn));
alert(str_replace(['a','b','c'],['x','y','z'],str,cfn));
alert('There were ' + cnt + ' replacements made.');
}
window.onload = init;
</script>
</head>
<body>
View the source for the code.
</body>
</html>