mirror of
https://github.com/TheAlgorithms/JavaScript.git
synced 2025-07-06 09:28:26 +08:00
Add reverse words (#162)
* add reverse words * Update ReverseWords.js * Update ReverseWords.js Co-authored-by: vinayak <itssvinayak@gmail.com>
This commit is contained in:
15
String/ReverseWords.js
Normal file
15
String/ReverseWords.js
Normal file
@ -0,0 +1,15 @@
|
|||||||
|
const reverseWords = (str) => {
|
||||||
|
// Split string into words
|
||||||
|
// Ex. "I Love JS" => ["I", "Love", "JS"]
|
||||||
|
const words = str.split(' ')
|
||||||
|
// reverse words
|
||||||
|
// ["I", "Love", "JS"] => ["JS", "Love", "I"]
|
||||||
|
const reversedWords = words.reverse()
|
||||||
|
// join reversed words with space and return
|
||||||
|
// ["JS", "Love", "I"] => "JS Love I"
|
||||||
|
return reversedWords.join(' ')
|
||||||
|
}
|
||||||
|
|
||||||
|
// testing
|
||||||
|
console.log(reverseWords('I Love JS'))
|
||||||
|
console.log(reverseWords('My Name Is JavaScript'))
|
Reference in New Issue
Block a user