Skip to content Skip to sidebar Skip to footer

Reverse A String In Js

I'm going through tutorials to code (I'm fairly new at this), and this particular exercise is racking my brain. Here are the parameters: Reverse the provided string. You may need

Solution 1:

Arrays have a method called reverse( ). The tutorial is hinting at using this.

To convert a string into an array of characters (in reality they're just single character strings), you can use the method split( ) with an empty string as the delimiter.

In order to convert the array back into a string, you can use the method join( ) again, with an empty string as the argument.

Using these concepts, you'll find a common solution to reversing a string.

functionreverseString(str) {
    return str.split( '' ).reverse( ).join( '' );
}

Solution 2:

Pretty manual way to accomplish this

var j = 'abcdefgh';
var k = j.split('');


var reversedArr = []
for(var i = k.length; i >= 0; i--) {
    reversedArr.push(k[i])
}

var reversedStr = reversedArr.join('')
console.log(reversedStr)

Solution 3:

You can read more here: http://eddmann.com/posts/ten-ways-to-reverse-a-string-in-javascript/

functionreverse(s) {
  var o = '';
  for (var i = s.length - 1; i >= 0; i--)
    o += s[i];
  return o;
}

Solution 4:

A string is an array of characters, so you can use the reverse function on the array to reverse it and then return it:

functionreverseString(str) {
    return str.split('').reverse().join('');
}

Solution 5:

var reversedStr = normalStr.split("").reverse().join("");

Post a Comment for "Reverse A String In Js"