Invert words in a string

Time:2020-3-22

Invert words in a string

First kind

export default (str) => {
  //Strings are separated by spaces, and arrays are saved. The order of array elements is the order of words
  let arr = str.split(' ')
  //Iterate through the array, then invert each element
  let result = arr.map(item => {
    return item.split('').reverse().join('')
  })
  return result.join(' ')
}

Second kinds

export default (str) => {
  //1. The strings are separated by spaces, and the array is saved. The order of elements in the array is the order of words
  //2. Traverse the array, and then invert each element
  return str.split(' ').map(item => {
    return item.split('').reverse().join('')
  }).join(' ')
}

Third kinds

export default (str) => {
  //1. The strings are separated by spaces, and the array is saved. The order of elements in the array is the order of words
  //2. Traverse the array, and then invert each element
  return str.split(/\s/g).map(item => {
    return item.split('').reverse().join('')
  }).join(' ')
}

Fourth kinds

export default (str) => {
  //1. The strings are separated by spaces, and the array is saved. The order of elements in the array is the order of words
  //2. Traverse the array, and then invert each element
  return str.match(/[\w']+/g).map(item => {
    return item.split('').reverse().join('')
  }).join(' ')
}

Invert words in a string