Here's a working code with comments to explain you what you are doing wrong:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" lang="en">
<head>
<title>Play with Code</title>
</head>
<body>
<form name="myform" id="form">
Reverse String: <input type="text" id="reverseString"/><br/>
<input type="submit" value="Submit"/>
</form>
<script>
function reverseString() {
var s = document.getElementById('reverseString').value;
// reverse should initialized as a empty String
// to prevent adding char to "undefined" string
var reversed = '';
for (var i = s.length - 1; i >= 0; i--) {
reversed += s[i];
}
document.getElementById('reverseString').disabled = true;
document.getElementById('reverseString').value = reversed;
}
function submit(ev) {
// preventDefault prevent the form to do his automatic
// behavior which submit the form with a new HTTP request
ev.preventDefault();
reverseString();
}
// Attach the event to the form
document.getElementById('form').addEventListener('submit', submit);
</script>
</body>
</html>
Answer from gaelgillard on Stack OverflowVideos
Here's a working code with comments to explain you what you are doing wrong:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" lang="en">
<head>
<title>Play with Code</title>
</head>
<body>
<form name="myform" id="form">
Reverse String: <input type="text" id="reverseString"/><br/>
<input type="submit" value="Submit"/>
</form>
<script>
function reverseString() {
var s = document.getElementById('reverseString').value;
// reverse should initialized as a empty String
// to prevent adding char to "undefined" string
var reversed = '';
for (var i = s.length - 1; i >= 0; i--) {
reversed += s[i];
}
document.getElementById('reverseString').disabled = true;
document.getElementById('reverseString').value = reversed;
}
function submit(ev) {
// preventDefault prevent the form to do his automatic
// behavior which submit the form with a new HTTP request
ev.preventDefault();
reverseString();
}
// Attach the event to the form
document.getElementById('form').addEventListener('submit', submit);
</script>
</body>
</html>
Working Demo
More Info on Debugging
//HTML
Reverse String: <input type="text" id="reverseString"/><br/>
<input type="button" value="Submit" onClick="funcreverse()"/>
//Script
function funcreverse () {
var s = document.getElementById('reverseString').value;
var reversed = '';
for (var i = s.length - 1; i >= 0; i--) {
reversed += s[i];
}
document.getElementById('reverseString').disabled = true;
document.getElementById('reverseString').value = reversed;
};
reverse() is a method of array instances. It won't directly work on a string. You should first split the characters of the string into an array, reverse the array and then join back into a string:
var backway = oneway.split("").reverse().join("");
Update
The method above is only safe for "regular" strings. Please see comment by Mathias Bynens below and also his answer for a safe reverse method.
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 mañana');
// → 'anã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 mañana'
Why? Because it contains an astral symbol (𝌆) (which are represented by surrogate pairs in JavaScript) and a combining mark (the ñ in the last mañ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 ã 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 mañana';
esrever.reverse(input);
// → 'anañam anañam rab 𝌆 oof'
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 mañana');
// → 'anã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 mañana'
Why? Because it contains an astral symbol (𝌆) (which are represented by surrogate pairs in JavaScript) and a combining mark (the ñ in the last mañ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 ã 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 mañana';
esrever.reverse(input);
// → 'anañam anañam rab 𝌆 oof'
As for the “in-place” part, see the other answers.