menu

JavaScript/Typescript - 16 Topics

DEEP DIVE INTO

JavaScript/Typescript

Topic:Reverse string

menu

The reverse() method is not available in string object it is an array method, so if you want to reverse a string then first of all you will have to convert your string into an array, reverse the array, and again join the array. Which will give an output as a string in reverse order.

javascriptconst str = "Hello, World!";
const reversedStr = str.split('').reverse().join('');
console.log(reversedStr); // "!dlroW ,olleH"

In the code above:

  • str.split('') splits the string into an array of characters.

  • .reverse() reverses the order of elements in the array.

  • .join('') joins the array elements back into a single string.

The above process will effectively reverse the characters in the string.

Keep in mind that this approach works for reversing the characters in a string, but it doesn't reverse the string's encoding or handle multibyte characters properly. If your string contains non-ASCII characters or multibyte characters, you should be cautious when using this method, as it may not work as expected for all character encodings.

warning
1280 x 720 px