欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

【刷题】把字符串中包含5个和5个以上的单词翻转,输出新字符串

程序员文章站 2022-06-09 18:37:33
...

原题目:

Write a function that takes in a string of one or more words, and returns the same string, but with all five or more letter words reversed (Just like the name of this Kata). Strings passed in will consist of only letters and spaces. Spaces will be included only when more than one word is present.
Examples: spinWords( “Hey fellow warriors” ) => returns “Hey wollef sroirraw” spinWords( “This is a test”) => returns “This is a test” spinWords( “This is another test” )=> returns “This is rehtona test”

我的代码实现:

function spinWords(str){
  //TODO Have fun :)
  var arr = str.split(' ');
  var len = arr.length;
  for (var i = 0; i < len; i++){
     arr[i].length > 4 ? arr[i] = arr[i].split('').reverse().join('') : arr[i]
  }
  return arr.join(' ');
}

还是too young too simple. 这年代怎么还用for循环呢?
看看大佬的代码:

function spinWords(words){
  return words.split(' ').map(function (word) {
    return (word.length > 4) ? word.split('').reverse().join('') : word;
  }).join(' ');
}

直接用map遍历数组,比我for循环高级多了,直接一条链下来了。另外人家命名也很好:words,word。
另外也可以把map回调换成ES6的箭头函数:

function spinWords(str){
  return str.split(' ').map( w => w.length<5 ? w : w.split('').reverse().join('') ).join(' ');
}

还有大佬用正则来替换(回头再好好学些正则表达式吧):

function spinWords(string){
  return string.replace(/\w{5,}/g, function(w) { return w.split('').reverse().join('') })
}