Here is the simplest way to do without using any javascript inbuilt function.
function reverse1(str){
let r = "";
for(let i = str.length-1; i >= 0; i--){
r += str[i];
}
return r;
}
console.log(reverse1("javascript"))
Answer from vipul suryavanshi on Stack OverflowHere is the simplest way to do without using any javascript inbuilt function.
function reverse1(str){
let r = "";
for(let i = str.length-1; i >= 0; i--){
r += str[i];
}
return r;
}
console.log(reverse1("javascript"))
Create a new string and add all the chars from the original string to it backwards:
function reverse1(str){
var r = "";
for(var i = str.length - 1; i >= 0; i--){
r += str.charAt(i);
}
return r;
}
Then just say:
str = reverse1(str);
javascript - How do you reverse a string in-place? - Stack Overflow
Reverse string in JavaScript without using reverse() - Code Review Stack Exchange
javascript - How to reverse strings in js without using methods - Stack Overflow
How would you reverse a string in JavaScript without using split(), reverse(), or join()?
Videos
As long as you're dealing with simple ASCII characters, and you're happy to use built-in functions, this will work:
function reverse(s){
return s.split("").reverse().join("");
}
If you need a solution that supports UTF-16 or other multi-byte characters, be aware that this function will give invalid unicode strings, or valid strings that look funny. You might want to consider this answer instead.
The array expansion operator is Unicode aware:
function reverse(s){
return [...s].reverse().join("");
}
Another Unicode aware solution using split(), as explained on MDN, is to use a regexp with the u (Unicode) flag set as a separator.
function reverse(s){
return s.split(/(?:)/u).reverse().join("");
}
The following technique (or similar) is commonly used to reverse a string in JavaScript:
// Donโt use this!
var naiveReverse = function(string) {
return string.split('').reverse().join('');
}
In fact, all the answers posted so far are a variation of this pattern. However, there are some problems with this solution. For example:
naiveReverse('foo ๐ bar');
// โ 'rab ๏ฟฝ๏ฟฝ oof'
// Where did the `๐` symbol go? Whoops!
If youโre wondering why this happens, read up on JavaScriptโs internal character encoding. (TL;DR: ๐ is an astral symbol, and JavaScript exposes it as two separate code units.)
But thereโs more:
// To see which symbols are being used here, check:
// http://mothereff.in/js-escapes#1ma%C3%B1ana%20man%CC%83ana
naiveReverse('maรฑana manฬana');
// โ 'anaฬnam anaรฑam'
// Wait, so now the tilde is applied to the `a` instead of the `n`? WAT.
A good string to test string reverse implementations is the following:
'foo ๐ bar maรฑana manฬana'
Why? Because it contains an astral symbol (๐) (which are represented by surrogate pairs in JavaScript) and a combining mark (the nฬ in the last manฬana actually consists of two symbols: U+006E LATIN SMALL LETTER N and U+0303 COMBINING TILDE).
The order in which surrogate pairs appear cannot be reversed, else the astral symbol wonโt show up anymore in the โreversedโ string. Thatโs why you saw those ๏ฟฝ๏ฟฝ marks in the output for the previous example.
Combining marks always get applied to the previous symbol, so you have to treat both the main symbol (U+006E LATIN SMALL LETTER N) as the combining mark (U+0303 COMBINING TILDE) as a whole. Reversing their order will cause the combining mark to be paired with another symbol in the string. Thatโs why the example output had aฬ instead of รฑ.
Hopefully, this explains why all the answers posted so far are wrong.
To answer your initial question โ how to [properly] reverse a string in JavaScript โ, Iโve written a small JavaScript library that is capable of Unicode-aware string reversal. It doesnโt have any of the issues I just mentioned. The library is called Esrever; its code is on GitHub, and it works in pretty much any JavaScript environment. It comes with a shell utility/binary, so you can easily reverse strings from your terminal if you want.
var input = 'foo ๐ bar maรฑana manฬana';
esrever.reverse(input);
// โ 'ananฬam anaรฑam rab ๐ oof'
As for the โin-placeโ part, see the other answers.
One array to rule them all
You do not need to create two arrays; one is enough. Simply swap slots until you've reached the "middle" of the array.
Declare your variables
It is better to use the
varkeyword to define your variables. Otherwise, they are declared on the top-level scope, i.e; they become global, and may be accessed and modified by other functions.Why not use
reverse()?You do not say why you cannot use built-in functions. If you happen to have some base code which overrides native functions, then some groaning and roaring is in order.
function reverse(str) {
var chars = str.split("");
var length = chars.length;
var half = length / 2;
for (var ii = 0; ii < half; ii++) {
var temp = chars[ii];
var mirror = length - ii - 1;
chars[ii] = chars[mirror];
chars[mirror] = temp;
}
return chars.join("");
}
console.log(reverse("abcd"));
console.log(reverse("abcde"));
I was wondering if there's a need to split at all, because characters are accessible directly using String#charAt.
This implementation (which is almost the same as yours - only with the split) should be among the fastest.
function reverse(str) {
var result = [];
for (var i = str.length - 1; i >= 0; i--) {
result.push(str.charAt(i));
}
return result.join("");
}
console.log(reverse("abcde"));
According to some benchmark, String concatenation is better optimized than Array.join, it also makes the code cleaner:
function reverse(str) {
var result = "";
for (var i = str.length - 1; i >= 0; i--) {
result += str.charAt(i);
}
return result;
}
console.log(reverse("abcde"));
As a side-note, you can get creative by using Array.prototype.reduce and allow JavaScript duck-type the String as an Array.
function reverse(str) {
return Array.prototype.reduce.call(str, function(result, c) {
return c + result;
}, "");
}
console.log(reverse("Hello world!"));
And going further you can make an ES6 one-liner:
let reverse = str => Array.prototype.reduce.call(str, (result, c) => c + result, "");
console.log(reverse("Hello world!"));
JSFiddle forked from @Andreas: https://jsfiddle.net/kazenorin/6shbv6hs/2/
Interviewers love to ask: "Reverse a string without using JavaScript's built-in methods." ๐ฅ
I tried solving it manually by:
-
Starting from the last character
-
Appending each character to a new string
I explained my approach with code here if anyone wants to check it out: https://www.youtube.com/watch?v=N_UVJlnmD7w
Curious โ how would you solve it differently? Would love to learn new tricks! ๐
Arrays can be used like stacks out of the box. And stacks are LIFO, which is what you need.
function reverseWords(str) {
var word, words, reverse;
words = str.match(/(?:\w+)/g);
reverse = '';
while(word = words.pop()) {
reverse += word + ' ';
}
return reverse.trim();
}
reverseWords('hello world');
Or use the call stack as your stack:
function reverseWords(str) {
var result = '';
(function readWord(i = 0) {
var word = '';
if(i > str.length) {
return '';
}
while(str[i] !== ' ' && i < str.length) {
word += str[i];
i++;
}
readWord(++i); // Skip over delimiter.
result += word + ' ';
}());
return result.trim();
}
reverseWords('hello world');
Another idea for reversing the words in a String is using a Stack data structure. Like so:
var newString = "";
var theString = prompt("Enter a Phrase that you would like to reverse (Ex. Hello world)");
var word = "";
var c;
var stack = [];
for (var i = 0, len = theString.length; i < len; i++) {
c = theString[i];
word += c;
if (c == " " || i == (len-1)) {
word = word.trim();
stack.push(word);
word = "";
}
}
while (s = stack.pop()) {
newString += s + " ";
}
console.log(newString);
Strings are immutable in JavaScript. Therefore, they cannot be changed in-place. Any new string requires a new memory allocation, even when doing something as simple as
const str1 = "hello";
const str2 = str[0];
Leaves two strings in memory: "hello" and "h".
Since any attempt to produce a string will create at least one new string, it is therefore impossible to reverse a string without allocating space for a new string where the characters are reversed.
The minimum space complexity for this task is thusO(n) - scales linearly with the string length. Creating an array which can be rearranged in-place and then combined back to the reversed string fulfils this.
Here is a recursive way of doing it:
const rev = s => s.length>1 ? s.at(-1)+rev(s.slice(0,-1)) : s;
console.log(rev("This is a test string."))