0

I am a beginner at JavaScript and I was working on this exercise where I am asked to reverse a string. The string I am to reverse is w3resource. It is supposed to be backwards. I couldn't find any string methods that would do what I was trying to get done. So I converted the string to an array. The JavaScript code is below the HTML:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>Document</title>
    </head>
    <body>
        String manipulation with 
        <pre id="target">w3resource</pre>
        <script src="script.js"></script>
    </body>
</html>
var word = document.getElementById('target');
var arr = Array.from(word.innerText);
console.log(arr)
var newArr = []

function rearrangement(arr1, arr2)
{
    for(var i = 9; i < arr1.length; i--)
        arr2.unshift(arr1.pop(i))

    return arr2
}

console.log(rearrangement(arr, newArr))
Isaac Corbrey
  • 553
  • 3
  • 20
Kazim Shabbir
  • 145
  • 1
  • 12
  • Sorry, but what is your actual question? Just as a code organization suggestion, I would suggest defining a "reverseString(string)" function instead of doing some of the work inside the function and some of it outside the function (namely, the call to Array.from() seems odd). – Everett Jun 05 '20 at 01:52
  • 1
    Does this answer your question? [How do you reverse a string in place in JavaScript?](https://stackoverflow.com/questions/958908/how-do-you-reverse-a-string-in-place-in-javascript) – user120242 Jun 05 '20 at 02:12

2 Answers2

2

You can do this by converting the string into an array, then reversing the array and joining it back together as follows:

const reverseString = word =>
    [...word].reverse().join('')

If you don't need this as a function (which is recommended to make it more clear what's happening), you can just execute this inline:

let reversedWord = [...word].reverse().join('')
Isaac Corbrey
  • 553
  • 3
  • 20
myrdstom
  • 156
  • 3
  • 15
  • 1
    This is a very frequent solution but `split('')` does not work with UTF-16 (multi-byte) characters. More widely usable is `[...word]` or `Array.from(word)`. See https://stackoverflow.com/questions/958908/how-do-you-reverse-a-string-in-place-in-javascript – jdaz Jun 05 '20 at 02:25
0

You don't really need to convert the string to an array (you can access each letter with str[i]), but if you do convert it to an array, you can just use reverse().

Array.from("test").reverse();
Gabriel
  • 2,170
  • 1
  • 17
  • 20
  • 1
    I think you forgot a `join()` at the end to convert it back to a string: `Array.from("test").reverse().join("")`. – nicoqh Jun 05 '20 at 01:49