Search and Replace Problem

Search and Replace Problem
0.0 0


Whats wrong in my code it works fine but not on all inputs.
i am confused…

function myReplace(str, before, after) {
 var arr=[];
  return str.replace(before,after);
myReplace("This has a spellngi error", "spellngi", "spelling");
//myReplace("A quick brown fox jumped over the lazy dog", "jumped", "leaped"); //works fine


You are forcing the replacement word to uppercase.


Using the test case of the following, I summarize what your code actually does in the steps at the bottom.

myReplace('This has a spellngi error', 'spellngi', 'spelling');

#1) Create an array of characters from the after variable and assign it’s reference to the arr variable.

At this point arr refers to [ ‘s’, ‘p’, ‘e’, ‘l’, ‘l’, ‘i’, ‘n’, ‘g’ ]

#2) Check if the first element of arr (which is ‘s’) is equal to the upperCase version of ‘s’ (which would be ‘S’). Since it is not the else block of code executes, which assigns the upperCase version of ‘s’ (which is ‘S’) to the first element of arr.

At this point arr now refers to [ ‘S’, ‘p’, ‘e’, ‘l’, ‘l’, ‘i’, ‘n’, ‘g’ ]

#3) You assign the string created from joining the elements of arr back to after.

At this point after is ‘Spelling’

#4) Finally, you replace the first instance of before (which is ‘spellngi’) in str with after (which is ‘Spelling’) and return the replaced string back to the calling function.

The returned string is ‘This has a Spelling error’.


thanx @randelldawson @JohnnyBizzel

i just solved it another way…
function myReplace(str, before1, after1) {
var after=after1.split(’’);
var before=before1.split(’’);

return str.replace(before,after);
myReplace(“His name is Tom”, “Tom”, “john”);

i am new in programming that’s why my solutions are very simple.