Reversed Words CodeWars Question(1)
I'm currently revising my JavaScript knowledge using the CodeWars platform until I'm confident enough to go for Leetcode. So today, I stumbled upon a really easy problem, but I got stuck because I forgot a few important things in that question. Below is the question I got.
Complete the function that accepts a string parameter and reverses each word in the string. All spaces in the string should be retained.
Examples
"This is an example!" ==> "sihT si na !elpmaxe"
"double spaces" ==> "elbuod secaps"
Starting code is below.
function reverseWords(str) {
}
For this question, my first approach was first to split the string at the space (" ")
for that, I used,
let splitedArray = str.split(" ");
Then we need to create a new variable to add the reversed array.
let reversedArray = [];
Then I created a for loop, which has the length of splitedArray
for(let i = 0 ; i < splitedArray.length ; i++) {
}
I took the splitedArray[i]
and added that into word
and then created an empty string called reversedWord
to store the reverse word in each iteration
let word = splitArray[i];
let reversedWord = "";
Next, for loop is used to iterate over the characters of a word in reverse order.
for(let j = word.length - 1 ; j>=0 ; j--){
}
let j = word.length - 1
: Initializes the loop variablej
to the index of the last character in theword
string. The index is obtained by subtracting 1 from thelength
property of theword
string. This ensures that we start from the last character of the word.j >= 0
: Specifies the condition for executing the loop. The loop will continue if the value exceeds or equals 0. This condition ensures that we iterate until we reach the first character of the word.j--
: Decrements the valuej
by 1 after each iteration. This causes the loop to move backward through the characters of the word.
In the loop, I have written this line.
reversedWord += word[j];
it takes the reversed word and adds that into reversedWord
variable.
then outside of the nested for loop, I have pushed the newly created reversedWord
into reversedArray
using push()
method.
reversedArray.push(reversedWord);
These steps will give you the output of this.
const reversed = reverseWords("This is an example!");
console.log(reversed); // Output: "sihT si na !elpmaxe"
So the completed code is below.
function reverseWords(str) {
let splitArray = str.split(" ");
let reversedArray = [];
for (let i = 0; i < splitArray.length; i++) {
let word = splitArray[i];
let reversedWord = "";
for (let j = word.length - 1; j >= 0; j--) {
reversedWord += word[j];
}
reversedArray.push(reversedWord);
}
return reversedArray.join(" ");
}
This is not the optimal solution, but I'm still practicing and hoping to develop the knowledge on the way.