Reputation: 145
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))
Upvotes: 0
Views: 95
Reputation: 306
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('')
Upvotes: 2
Reputation: 2190
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();
Upvotes: 0