reverse a string using splice in javascript

To reverse a string using splice method in JavaScript, we can first convert the string to an array, then use the splice method to reverse the array, and finally join the reversed array back into a string. Here's the code to achieve this:

index.tsx
let str = "Hello World!";
let chars = str.split(""); // convert string to array of characters
chars.splice(0, chars.length, ...chars.reverse()); // reverse the array
let reversedStr = chars.join(""); // join the array back into a string
console.log(reversedStr); // Output: "!dlroW olleH"
289 chars
6 lines

In the above code, we first declare a string str and then convert it into an array of characters using the split method. Then using the splice method, we reverse the array by providing the start index as 0, the number of elements to remove as the length of the array, and the elements to add to the array as the reversed version of the array using the spread operator. Finally, we join the array back into a string using the join method and store it in the reversedStr variable. The output of the console.log statement is the reversed string "!dlroW olleH".

gistlibby LogSnag