1. 程式人生 > 其它 >JS實現特定字串反轉

JS實現特定字串反轉

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"


My Solutions:

function spinWords(string) {
  //TODO Have fun :)
  const str = string.split(' ')
  const reversed = []
  const unReversed = []
  const arr = []
  for (var i = 0; i < str.length; i++) {
    if (str[i].length >= 5) {
      const result = str[i].split('').reverse().join('')
      arr[i] 
= result } else { arr[i] = str[i] } } return(arr.join(' ')) }
function spinWords(string) {
  //TODO Have fun :)
  const word = string.split(' ')
  word.map((word) => {
    if (word.length > 4) {
      return word.split('').reverse().join('')
    } else {
      return word
    }
  }).join(
' ') }

Best Practices:

function spinWords(words){
  return words.split(' ').map(function (word) {
    return (word.length > 4) ? word.split('').reverse().join('') : word;
  }).join(' ');
}
function spinWords(string){
  return string.replace(/\w{5,}/g, function(w) { return w.split('').reverse().join('') })
}