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"
我希望函数返回“e”,这是唯一更改的部分,也称为替换部分,那么我应该如何做到这一点? 提前致谢。
最佳答案
您可以迭代所有字符并仅采用更改的字符。
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")));
关于javascript - 使用 Javascript 查找字符串中被替换的部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48355929/