- Published on
Reversing a string in javascript
- Authors
- Name
- John Mwendwa
- Github
- John
Reversing a string is not always as straight forward as the term indicates.
method 1
1const stringReverse = (s) => { 2 let str = ""; 3 for (let i = s.length - 1; i >= 0; i--) { 4 str += s[i]; 5 } 6 return str; 7};
method 2
1const stringReverse = (s) => { 2 let str = []; 3 for (let i = s.length - 1, j = 0; i >= 0; i--, j++) { 4 str[j] = s[i]; 5 } 6 return str.join(""); 7};
method 3 : Using built in split(), reverse() and join() methods
1const stringReverse = (s) => { 2 return s.split("").reverse().join(""); 3};
method 4 : Looping through each character
1const stringReverse = (s) => { 2 let reversed = ""; 3 4 for (let character of s) { 5 reversed = character + reversed; 6 } 7 return reversed; 8};
method 5 : Using reduce method
1const stringReverse = (s) => { 2 return s.split("").reduce((rev, char) => char + rev, ""); 3};
conclusion
In terms of performance and efficient use of memory and space,
I'd recommend using method 1
, method 2
and method 4
as they are very performant.