function myReplace(str, before, after) { //return str; if(before[0] === before[0].toUpperCase()){ after = after[0].toUpperCase() + after.slice(1); } str = str.replace(before,after); return str; } myReplace("A quick brown fox jumped over the lazy dog", "jumped", "leaped");
另外一种方法
function myReplace(str, before, after) { //return str; var re = /^[A-Z]/; if(re.test(before.charAt(0))){ after = after.charAt(0).toUpperCase() + after.slice(1); } str = str.replace(before,after); return str; } myReplace("A quick brown fox jumped over the lazy dog", "jumped", "leaped");