[8kyu]Exclamation marks series #4: Remove all exclamation marks from sentence but ensure a exclamation mark at the end of

该算法题来自于 codewars【语言: javascript】,翻译如有误差,敬请谅解~

[8kyu]Exclamation marks series #4: Remove all exclamation marks from sentence but ensure a exclamation mark at the end of_第1张图片

  • 任务
  • 删除句子中多余的感叹号,只在字符串结尾处有一个感叹号。假设输入数据始终为非空字符串,无需验证。
  • 例如:
    remove("Hi!") === "Hi!"
    remove("Hi!!!") === "Hi!"
    remove("!Hi") === "Hi!"
    remove("!Hi!") === "Hi!"
    remove("Hi! Hi!") === "Hi Hi!"
    remove("Hi") === "Hi!"

  • 解答【如解答有误,欢迎留言指正~】
  • 其一
const remove = s => s.replace(/!/g,'') + '!';
  • 其二
const remove = s => `${s.replace(/!/g,'')}!`
  • 其三
function remove(s){
      return s.replace(/!/g, '').concat('!');
}
  • 其四
function remove(s){
      s = s.split('!');
      return s.concat('!').join('');  
}
  • 其五
const remove = s => s.split("!").join("") + "!";
  • 其六
function remove(s){
      var string = "" ;  
      for (var i = 0; i < s.length; i++) {
        if ( s[i] !== "!") {
          string += s[i];
        }
      }
      return string + "!";  
}
  • 其七
function remove(s){
      let arr = s.split('');
      let result = arr.filter(function(item) {
        if (item !== '!') {
          return item;
        }
      })
      result.push('!');
      return result.join('');
}
  • 其八
function remove(s){
      return s.split("").filter(i => i!= "!").join("") + "!";
}

你可能感兴趣的:([8kyu]Exclamation marks series #4: Remove all exclamation marks from sentence but ensure a exclamation mark at the end of)