0

can anyone please tell me how to reverse a given string without using ANY built in functions?

I have tried following ones, but in all cases there is some built in functions involved

function reverseString(str){        
    return str.split("").reverse().join("");    
}
reverseString("I love coding");

function reverseString(str){
    var myArray = [];
    for(var i = 0; i <= str.length; i++ ){
        myArray.push(str.charAt(str.length - i));
    }
    return myArray.join("");
}
reverseString("I love coding");

function reverseString(str){
    var reversedString = '';
    for(var i = str.length -1 ; i >= 0; i--){
        reversedString += str[i];
    }

    return reversedString;
}
reverseString("I love coding");

function reverseString(str){
    var newArray = [];
    for(var i = str.length -1, j = 0; i >= 0; i--, j++){
        newArray[j] = str[i];
    }
    return newArray.join("");
}
reverseString("I love coding");
Aditya Kumar
  • 165
  • 1
  • 1
  • 16
  • 6
    There is no built-in function involved in your 3rd example. – Pointy Jul 01 '15 at 12:15
  • I don't want to use any extra var also. Is it possible? – Aditya Kumar Jul 01 '15 at 12:16
  • thirs function() is perfect . no built in function is there except join()... – kavetiraviteja Jul 01 '15 at 12:16
  • 2
    No, it is not possible. Strings are immutable, so you'll have to build a new string. – Pointy Jul 01 '15 at 12:17
  • for swapping you need extra var|array. I am trying to avoid all those things. @ravi – Aditya Kumar Jul 01 '15 at 12:19
  • None of the above algorithms account for Unicode combing characters or surrogate pairs, and doing so without using ***ANY** built in function* seems unlikely. See e.g. https://mathiasbynens.be/notes/javascript-unicode#reversing-strings and [this answer](https://stackoverflow.com/a/16776380) to [Reversing a string in JavaScript](https://stackoverflow.com/q/1611427) for a discussion of how to reverse such sequences correctly. – dbc Jul 06 '19 at 09:18

2 Answers2

0

to comply with requirement of no natives and no var declaration I've cheated.

named arguments can be reassigned.

var s = 'foobar';

function r(e,v,r){
  for(r=e.length,v='';r;)v+=e[--r];return v;    
}

console.log(r(s));
Dimitar Christoff
  • 26,147
  • 8
  • 50
  • 69
0

It is very simple

var name = 'bhaurao';
var newName = '';
for(i in name){
  newName = name[i] + newName;

}
console.log("reverse string is "+newName);

You can check example here Click here

trincot
  • 317,000
  • 35
  • 244
  • 286
Bhaurao Birajdar
  • 1,437
  • 11
  • 15