How To Reverse A String In JavaScript - Mastering JS
Maybe your like
To reverse a string, you can transform the string into an array and then use JavaScript arrays' built-in reverse() method.
Array.from('help').reverse().join(''); // plehor
let str = 'help'; [...str].reverse().join(''); // plehYou can also use str.split('').reverse().join(''), but we recommend using Array.from() or the spread operator. The split() method does not handle UTF-16 characters, like emojis.
Reverse a String Without Built-in Methods
Reversing a string without any built-in methods is a common interview question. You can use a for loop to iterate through the string in reverse as shown below.
let str = 'hello world'; let reversed = ''; for(let i = str.length - 1; i >= 0; i--) { result += str[i]; } return result;Using Recursion
Another approach for reversing a string is using recursion. The idea is that you can break down the problem of reversing a string into two steps:
- Swap the first and last characters of the string
- Reverse everything except for the first and last characters
More Fundamentals Tutorials
- The `setTimeout()` Function in JavaScript
- JavaScript Array flatMap()
- How to Get Distinct Values in a JavaScript Array
- Check if a Date is Valid in JavaScript
- Encode base64 in JavaScript
- Check if URL Contains a String
- JavaScript Add Month to Date
Tag » How To Reverse A String Javascript
-
Three Ways To Reverse A String In JavaScript - FreeCodeCamp
-
How Do You Reverse A String In-place In JavaScript? - Stack Overflow
-
JavaScript Program To Reverse A String - Programiz
-
Reverse A String In JavaScript - GeeksforGeeks
-
How To Reverse A String In JavaScript
-
How To Reverse A String In JavaScript - Stack Abuse
-
Three Ways To Reverse A String In JavaScript - Medium
-
Methods To Reverse String In JavaScript - Flexiple
-
How Do You Reverse A String In Place In JavaScript? - Tutorialspoint
-
verse() - JavaScript - MDN Web Docs
-
How Do I Reverse A String In JavaScript? - ReqBin
-
Reversing A String Using JavaScript
-
How To Reverse A String In Python - W3Schools
-
Reverse A String In JavaScript - DEV Community