要求
使用给定的参数对句子执行一次查找和替换,然后返回新句子。
第一个参数是将要对其执行查找和替换的句子。
第二个参数是将被替换掉的单词(替换前的单词)。
第三个参数用于替换第二个参数(替换后的单词)。
注意:替换时保持原单词的大小写。例如,如果你想用单词 "dog" 替换单词 "Book" ,你应该替换成 "Dog"。
参考
样本
myReplace("Let us go to the store", "store", "mall") 应该返回 "Let us go to the mall"。
myReplace("He is Sleeping on the couch", "Sleeping", "sitting") 应该返回 "He is Sitting on the couch"。
myReplace("This has a spellngi error", "spellngi", "spelling")应该返回 "This has a spelling error"。
myReplace("His name is Tom", "Tom", "john") 应该返回 "His name is John"。
myReplace("Let us get back to more Coding", "Coding", "algorithms") 应该返回 "Let us get back to more Algorithms"。
解法
function myReplace(str, before, after) {
var bArr = str.split(' ');
for(var i=0;i<bArr.length;i++){
if(bArr[i].toUpperCase()==before.toUpperCase()){
if(isUp(bArr[i])){
bArr[i] = after[0].toUpperCase()+after.substring(1,after.length);
}else{
bArr[i] = after;
}
}
}
str = bArr.join(' ');
return str;
}
function isUp(str){
return (/^[A-Z]+/.test(str[0]))?true:false;
}
myReplace("A quick brown fox jumped over the lazy dog", "jumped", "leaped");

本文介绍了一个JavaScript函数实现的具体案例,该函数能够对指定的句子进行精确的查找与替换操作,并保持原有单词的大小写不变。通过实际例子展示了如何使用正则表达式和字符串操作来完成这一任务。
1万+

被折叠的 条评论
为什么被折叠?



