javascript str_replace equivalent
August 31st, 2007 • javascript, snippets
I needed the equivalent of str_replace in JavaScript and was able to fish up this nifty piece of code! Enjoy.
/**
* str_replace
*
* This function returns a string or an array with all occurrences of
* [search] in [subject] replaced with the given [replace] value.
* If you don't need fancy replacing rules (like regular expressions), you should always use this function.
*
* @param string search
* @param string replace
* @param string string
*/
function str_replace (search, replace, subject)
{
var result = "";
var oldi = 0;
for (i = subject.indexOf (search); i > -1; i = subject.indexOf (search, i))
{
result += subject.substring (oldi, i);
result += replace;
i += search.length;
oldi = i;
}
return result + subject.substring (oldi, subject.length);
}
You might also want to look at these posts
4 Responses (Add Your Comment)
-
-
evgeny February 20, 2008at 4:12 am
thanks a lot for this script!
-
This script helped me out too!
Thank you very much!
-
Thanks, this was a nice copy and drop help!
We did some development on geotargetting ads via javascript. This post was of some help. Thx for this comment!