javascript - Replacing word in a string -


i want replace word in string word code not work.

note: preserve case of original word when replacing it. example, if mean replace word "book" word "dog", should replaced "dog"

what wrong in code ?

function replace(str, before, after) {        // find index before on string     var index = str.indexof(before);     var dogru = before[0] === before[0].touppercase();     var yanlıs = after[0] === after[0].touppercase();      // check see if first letter uppercase or not     if (dogru !== yanlıs) {         if(dogru)             after = after.charat(0).touppercase() + after.slice(1);         else             after = after.charat(0).tolowercase() + after.slice(1);     }      // replace original str edited one.     var str1 = str.split(' ');      str1.splice(str1.indexof(before),1, after);      return str1.join(' '); }  myreplace("a quick brown fox jumped on lazy dog", "jumped", "leaped"); 

you're over-complicating things friend. use replace() http://www.w3schools.com/jsref/jsref_replace.asp


Comments