W3Cschool中级脚本算法(5.字符串查询替换算法挑战)

字符串查询替换算法挑战


问题:

使用给定的参数对字符串执行一次查找和替换,然后返回新字符串。

第一个参数是将要对其执行查找和替换的字符串。

第二个参数是将被替换掉的单词(替换前的单词)。

第三个参数用于替换第二个参数(替换后的单词)。

注意:替换时保持原单词的大小写。例如,如果你想用单词 "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"。


问题答案:

if (before.charAt(0).toUpperCase() === before.charAt(0)) {
    after = after.charAt(0).toUpperCase() + after.substr(1);
  }
  return str.replace(before, after);

题目链接:

https://www.w3cschool.cn/codecamp/search-and-replace.html

猜你喜欢

转载自blog.csdn.net/qq_42044073/article/details/82620621