Reversing a string in JavaScript

Viewed 94357

I'm trying to reverse an input string

var oneway = document.getElementById('input_field').value();
var backway = oneway.reverse();

but firebug is telling me that oneway.reverse() is not a function. Any ideas?

Thank you

17 Answers

I like to share some notable implementations for string reverse.

  1. split,reverse,join
const reverseString = (str) => str.split('') .reverse() .join('');
  1. reduce
const reverseString =(str) => [...str].reduce((acc, cur) => cur + acc);
  1. append last one by one

const reverseString = (str) => {
    const ary = [];
    for(let char of str) {
        ary.unshift(char);
    }
    return ary.join('');
}

  1. recursion
const reverseString =(str)=> (str === '') ? '' : reverseString(str.substr(1)) + str[0];
  1. two pointer approach
const reverseString = (str) =>  {
    const strArr = Array.from(str);
    let start = 0;
    let end = str.length - 1;    
    while (start <= end) {
        const temp = strArr[start];
        strArr[start] = strArr[end];
        strArr[end] = temp;
        start++;
        end--;
    }
    return strArr.join("");
}

//Using reverse with split, reverse , join
function reverseString1(str) {
  return str
    .split('') // alternative [...str], Array.from(str)
    .reverse() // alternative .sort(() => -1)
    .join('');
}

// Using reduce 
function reverseString2(str) {
      return [...str].reduce((accumulator, current) => current + accumulator) // reduce from left to right
  //alternative [...str].reduceRight((accumulator, current) => accumulator + current); // reduce right to left
}

// append to last one by one
function reverseString3(str){
    const ary = [];
    for(let char of str) {
        ary.unshift(char);
    }
    return ary.join('');
}

// recursion with ternary with substr 
function reverseString4(str) {
    return (str === '') ? '' : reverseString4(str.substr(1)) + str[0];
}


// two pointer approach [less time complexity O(n)] 
// front back chars exchanging
function reverseString5(str) {
    const strArr = Array.from(str); // alternative [...str],str.split('')
    let start = 0;
    let end = str.length - 1;    
    while (start <= end) {
        const temp = strArr[start];
        strArr[start] = strArr[end];
        strArr[end] = temp;
        start++;
        end--;
    }
    return strArr.join("");
}


console.log(reverseString1("Hello World"))
console.log(reverseString2("Hello World"))
console.log(reverseString3("Hello World"))
console.log(reverseString4("Hello World"))
console.log(reverseString5("Hello World"))
//=> dlroW olleH

Note: Built-in method works well for ASCII inputs, not unicode things.. so use spread operation inspite of split. Check out split vs spread implementation

Extra: In-Place string reverse is not possible in JS. Check out in-place reverse

Reverse String using function parameter with error handling :

function reverseString(s) 
{
   try
   {
      console.log(s.split("").reverse().join(""));
   }
   catch(e)
   {
      console.log(e.message);
      console.log(s);
   }   
}

If it's necessary to revert the string, but return the original value of the error:

function reverseString(s) {
    let valuePrintS;
    try {
        valuePrintS = s.split("").reverse().join("");    
    } catch {
        console.log("s.split is not a function");
        valuePrintS = s;
    } finally {
        console.log(valuePrintS);
    }
}

I believe most performant solution with reduce like in https://stackoverflow.com/a/68978553/5018572 post

function reverse(str) {
  return str.split("").reduce((final, letter) => letter + final);
}

console.log(reverse("Armaggedon"));

Related