javascript str_replace equivalent

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

  • Wordpress mysqli 2.9 Database Class Patch
  • Google competing with code search sites
  • Google Promote
  • About Thomas
  • Tekken Movie Trailer
  • 

    4 Responses (Add Your Comment)

    1. We did some development on geotargetting ads via javascript. This post was of some help. Thx for this comment!

    2. thanks a lot for this script!

    3. This script helped me out too!

      Thank you very much!

    4. Thanks, this was a nice copy and drop help!

    Leave a Reply

    Formatting: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

    Archives

    Twitter!