使用給定的參數對句子執行一次查找和替換,然後返回新句子。
第一個參數爲搜索字符串,第二個參數爲搜索目標,第三個參數爲替換字符串 。
注意:第二個參數首字母大寫,第三個參數首字母也要大寫。
function myReplace(str, before, after) {
if (before.charAt(0).toUpperCase() === before.charAt(0)) {
after = after.charAt(0).toUpperCase() + after.substr(1);
}
return str.replace(before, after);
}
myReplace("A quick brown fox jumped over the lazy dog", "jumped", "leaped");