From e0789bccde6ca70156d3c84efb61fdb6b5f5459e Mon Sep 17 00:00:00 2001 From: Abhi Ramani Date: Sun, 10 May 2020 00:25:56 +0530 Subject: [PATCH] Add reverse words (#162) * add reverse words * Update ReverseWords.js * Update ReverseWords.js Co-authored-by: vinayak --- String/ReverseWords.js | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 String/ReverseWords.js diff --git a/String/ReverseWords.js b/String/ReverseWords.js new file mode 100644 index 000000000..0f0b92a28 --- /dev/null +++ b/String/ReverseWords.js @@ -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'))