Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Cover image for 3 Ways to Reverse a String in JavaScript
Ahmad Adibzad
Ahmad Adibzad

Posted on • Edited on

     

3 Ways to Reverse a String in JavaScript

In this post, you’ll learn how to work with the string.split(), string.join() functions, and finally spread operator.

JavaScript is a fantastic programming language that allows us to write code differently. Reversing a string in JavaScript is simple. Assuming we have a string like “JavaScript forever” we want to reverse all the characters of that. Let’s get started to do it.

1. Using loops

In most programming languages, and for new developers, using loops is the first way they can do it. Since the string is an iterable type in JavaScript, you can iterate through each character from the last to the first.

conststr="JavaScript forever";letreversed="";for(leti=str.length-1;i>=0;i-){reversed+=str[i];}console.log(reversed);// reverof tpircSavaJ
Enter fullscreen modeExit fullscreen mode

2. Using the split and join functions

In this way, you need to convert the string to an array. In JavaScript, you can split string characters into an array by using the split() function.

conststr="A text";constarr=str.split('');// ['A', ' ', 't', 'e', 'x', 't']constreversedArr=arr.reverse();// ['t', 'x', 'e', 't', ' ', 'A']constreversedStr=reversedArr.join('');// txet Aconsole.log(reversedStr);// txet A
Enter fullscreen modeExit fullscreen mode

You can merge all the lines into one line:

constresult=original.split('').reverse().join('');
Enter fullscreen modeExit fullscreen mode

3. Using the spread operator

Still looking for an advanced way? The spread operator (...) allows us to create a real copy of an iterable value and put it into an object or array. So here, the spread operator can be used instead of the split() function to make an array from the string:

conststr="A text";constarr=[...str];// Creates an array of string charactersconstreversedArr=arr.reverse();constreversedStr=reversedArr.join('');console.log(reversedStr);// txet A
Enter fullscreen modeExit fullscreen mode

Of course, You can merge them all into one line:

constresult=[...str].reverse().join('');
Enter fullscreen modeExit fullscreen mode

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Full-Stack Developer
  • Work
    Developer
  • Joined

More fromAhmad Adibzad

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp