Training, Open Source computer languages
PerlPHPPythonMySQLApache / TomcatTclRubyJavaC and C++LinuxCSS 
Search for:
Home Accessibility Courses Diary The Mouth Forum Resources Site Map About Us Contact
Python, Lua and Tcl - public course schedule [here]
Private courses on your site - see [here]
Please ask about maintenance training for Perl, PHP, Java, C, C++, Ruby, MySQL and Linux / Tomcat systems

Posted by Stooshie (Stooshie), 23 September 2002
Not sure if this is the right forum for this.

The javascript String object has a replace method.
String.replace(regexp, replacement)

which is fine, but I wanted a function to search and replace one string with another string in the main string (which you can probably do with the above function, but I wanted the challenge  )

I started thinking about looping round the string, checking for a match to the replace string, deleting the number of characters = length of replace string, inserting the with string and moving on the length of the with string etc...

Then I found this Genius piece of code (the genius is in it's simplicity, I think).

Maybe the experts on this board have seen it before, but hey, I was amazed.
function strReplace(s, r, w){
     return s.split(r).join(w);

Hope somebody finds it useful.

Posted by admin (Graham Ellis), 23 September 2002
Hi ... welcome ...

Javascript doesn't have a huge presence here - I guess that I (i'm the board's administratror) and most of the folks who come here are much more server side that client side folks, and that on the server we tend to be much more along the PHP/Perl lines than the ASP/.NET side where you can embed server side Javascript.   Having said that - yes, relevant, welcomed than you.

Personally, I tend to keep the JavaScript I embed in my web pages to a minimum in orer to avoid producing browser-specific pages .... although that might b emore for historic reasons and the fact that I've got more than enough to keep in my brain with all the other languages.

Stooshie, your Java script is elegant.  At first, no doubt it seems an extaordinary way of replacing strings by splitting and joining in this way - but if you look at a language like PHP, you'll find that the recommended way of doing something like this is
     a) explode the string at the string you want to be replaced
     b) implode the string, joining with the replacement string.

This page is a thread posted to the opentalk forum at and archived here for reference. To jump to the archive index please follow this link.

You can Add a comment or ranking to this page

© WELL HOUSE CONSULTANTS LTD., 2018: Well House Manor • 48 Spa Road • Melksham, Wiltshire • United Kingdom • SN12 7NY
PH: 01225 708225 • FAX: 01225 793803 • EMAIL: • WEB: • SKYPE: wellho