Thomas Hambach - Web engineer

Web development & web design
home   -   portfolio   -   resume -   contact
Vroooooooaaaap, i'm an airplane
August 31st, 2007

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26

/**
* 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);
}

Posted in javascript, snippets |

Related posts


3 Responses to “javascript str_replace equivalent”



Leave a Reply

copyright 2008 by http://www.rdlt.com
Entries (RSS) - Register - Log in
Wordpress - RDLT Media - mortgage companies