挑战:
参考 字符串查询替换算法挑战
使用给定的参数对字符串执行一次查找和替换,然后返回新字符串。
第一个参数是将要对其执行查找和替换的字符串。
第二个参数是将被替换掉的单词(替换前的单词)。
第三个参数用于替换第二个参数(替换后的单词)。
注意:替换时保持原单词的大小写。例如,如果你想用单词 “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”。
答案:
方法 | 描述 |
---|---|
charAt() | 返回在指定位置的字符。 |
toUpperCase() | 把字符串转换为大写。 |
substr() | 从起始索引号提取字符串中指定数目的字符。 |
replace() | 替换与正则表达式匹配的子串。 |
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");
运行结果:
A quick brown fox leaped over the lazy dog
在线测试: