We can easily reverse a string in JavaScript using the JavaScript split(), reverse() and join() methods. Below is a function we will create to reverse a string.
function reverseString(str){
var newStringArr = str.split("");
newStringArr.reverse();
newStringArr = newStringArr.join("");
return newStringArr;
};
Here is the function in use with an example string:
function reverseString(str){
var newStringArr = str.split("");
newStringArr.reverse();
newStringArr = newStringArr.join("");
return newStringArr;
};
var someString = "Hello";
console.log(reverseWords(someString));
#Output:
olleH
When using string variables in JavaScript, we can easily perform string manipulation to change the values or order of the characters in our string.
One such manipulation is to reverse the characters in a string.
To reverse a string, we can first use the split() method to get an array of each character in the string, and then use the reverse() method to return the array with all of the characters in reverse.
After reversing the array we then join the characters back together using the JavaScript join() method.
Below is our function once again on how to reverse a string using JavaScript.
function reverseString(str){
var newStringArr = str.split("");
newStringArr.reverse();
newStringArr = newStringArr.join("");
return newStringArr;
};
Note that if we wanted to reverse a string with multiple words, we could use our same function. Here is an example:
function reverseString(str){
var newStringArr = str.split("");
newStringArr.reverse();
newStringArr = newStringArr.join("");
return newStringArr;
};
var someString = "This is an example string with words";
console.log(reverseWords(someString));
#Output:
sdrow htiw gnirts elpmaxe na si sihT
Also note that reversing a string is very similar to reversing words in a string, the main difference in the functions being that when using the split() and join() methods, we add a space split(” “), join(” “) when reversing words, and no space when reversing characters in a word, split(“”), join(“”).
Hopefully this article has been helpful for you to learn how to reverse a string using JavaScript.