码迷,mamicode.com
首页 > 其他好文 > 详细

FCC_Intermediate Algorithm Scripting_Search and Replace

时间:2020-03-03 15:04:24      阅读:52      评论:0      收藏:0      [点我收藏+]

标签:challenge   search   replace   arc   html   方法   -o   put   http   

1.任务及要求

Search and Replace 


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

第一个参数是将要对其执行查找和替换的句子。

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

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

注意:替换时保持原单词的大小写。例如,如果你想用单词 "dog" 替换单词 "Book" ,你应该替换成 "Dog"。

如果你被难住了,记得使用 Read-Search-Ask尝试与他人结伴编程、编写你自己的代码。

 测试数据:
 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"。

2.我的解法

function myReplace(str, before, after) {
 // 字符串首字母大写方法参考:
 // https://www.cnblogs.com/ToBeBest/p/9724955.html
  
  if(before.charAt(0)>‘A‘ && before.charAt(0) <‘Z‘) {
    after = after.slice(0,1).toUpperCase() + after.slice(1);
  }
  
  return str.replace(before,after);
}

myReplace("A quick brown fox jumped over the lazy dog", "jumped", "leaped");

 

FCC_Intermediate Algorithm Scripting_Search and Replace

标签:challenge   search   replace   arc   html   方法   -o   put   http   

原文地址:https://www.cnblogs.com/yoursatan/p/12402080.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!