To replace a word or characters in a string, using JavaScript.
Terms of Agreement:
By using this article, you agree to the following terms...
You may use
this article in your own programs (and may compile it into a program and distribute it in compiled format for languages that allow it) freely and with no charge.
You MAY NOT redistribute this article (for example to a web site) without written permission from the original author. Failure to do so is a violation of copyright laws.
You may link to this article from another website, but ONLY if it is not wrapped in a frame.
You will abide by any additional copyright restrictions which the author may have placed in the article or article's description.
You can cut that function to half the length and speed it up slightly using str.replace instead of using str.substring, like below. Otherwise it's good :) ------------------------------------ function str_replace(str,stra,strb) { while(str.indexOf(stra)!=-1) { str=str.replace(stra,strb); } return str; } ------------------------------------ (If this comment was disrespectful, please report it.)
8/13/2004 10:47:29 PM:
so, what's wrong with javascript's built-in string replace()?
e.g.
var foo = "foo"; var bar = "bar"; var str = "a string with the word foo in it"; str = str.replace(foo, bar);
if you need global replace, use regex:
var foo = "foo"; var bar = "bar"; var regex = new RegExp(foo, "gi"); var str = "string foo with foo in it foo many times foo"; str = str.replace(regex, bar);
(If this comment was disrespectful, please report it.)
Great Ideas shared, take one more I use. function ReplaceAll(varb, replaceThis, replaceBy) { newvarbarray=varb.split(replaceThis); newvarb=newvarbarray.join(r eplaceBy); return newvarb; } (If this comment was disrespectful, please report it.)
btw, I like your solution Rickard, simple and clear. Using regular expressions is probably the most 'correct' way thou. I probably wouldn't use the split and join method when Rickard's is it :)
Happy coding, Rd. (If this comment was disrespectful, please report it.)
Add Your Feedback
Your feedback will be posted below and an email sent to
the author. Please remember that the author was kind enough to
share this with you, so any criticisms must be stated politely, or they
will be deleted. (For feedback not related to this particular article, please
click here instead.)