2
function str_replace(str , part_to_replace , replace_with) { 
var res = str.replace(part_to_replace , replace_with);
return res;
}
console.log(str_replace("amir" , "ir" , "er")) //returns "amer" 

I want the function to return "e" which is the only part that changed aka replaced part so how i am supposed to do that ? thanks in advance.

Amir
  • 65
  • 6

2 Answers2

3

You could iterate all characters and take only the changed ones.

function check(a, b) {
    if (a.length !== b.length) { return; }
    
    return b
        .split('')                // take an array
        .filter(function (c, i) { // filter
            return a[i] !== c;    // check characters
        })
        .join('');                // return string
}

function str_replace(str, part_to_replace, replace_with) {
    return str.replace(part_to_replace, replace_with);
}

console.log(str_replace("amir", "ir", "er"));
console.log(check("amir", str_replace("amir", "ir", "er")));
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
  • This is a good answer, very clean. One issue may be that it simply returns if the two strings are not the same length. I think it is fair to assume that the replaced part may be longer than the part replaced. – vince Jan 20 '18 at 12:32
  • @vincecampanale, it could be shorter as well. what would you like to return in case of unequal length? – Nina Scholz Jan 20 '18 at 12:33
  • Yep could be shorter too :) -- not sure what the OP wants in this case. I was thinking it would be a simple difference between the two strings, regardless of length. Comparing each index, if the character isn't the same, the character at that index (in the new string) gets returned. – vince Jan 20 '18 at 12:36
1

It looks like you want an array of characters in the new string that were not present in the old one. This will do the trick:

function getDifference(oldStr, newStr) {
  // .split('') turns your string into an array of characters
  var oldSplit = oldStr.split(''); 
  var newSplit = newStr.split('');

  // then compare the arrays and get the difference
  var diff = [];
  for (var i = 0; i < newSplit.length; i++) {
    if (newSplit[i] !== oldSplit[i]) {
      diff.push(newSplit[i]);
    }
  }
  return diff;
}

var diff = getDifference('amir', str_replace('amir', 'ir', 'er'));
console.log(diff); // e
vince
  • 7,808
  • 3
  • 34
  • 41