Reverse a string in javascript without using any inbuilt function
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);
How to reverse words in a string instead of reversing the whole string?
you need to split the string by space
function reverseInPlace(str) {
var words = [];
words = str.match(/\S+/g);
var result = "";
for (var i = 0; i < words.length; i++) {
result += words[i].split('').reverse().join('') + " ";
}
return result
}
console.log(reverseInPlace("abd fhe kdj"))
Reverse whole string while keeping the spaces at the same position
You just need to make following change
//for (var i = spaces.length - 1; i >=0; i = i - 1) {
// array3.splice(spaces[i], 0, " ");
//}
for (var i = 0; i < spaces.length; i = i + 1) {
array3.splice(spaces[i], 0, " ");
}
You are reading spaces array in reverse but as the problem stated spaces should be at same place. Reading it from start to finish fixed the issue.
function reverseStr(input){
var array1 = [];
var array2 = [];
var nWord;
for (var i = 0; i < input.length; i++) {
array1.push(input[i]);
}
var spaces = [];
for (var i = 0; i < array1.length; i++) {
if(array1[i] == " ") {
spaces.push(i);
}
}
console.log(array1);
console.log(spaces);
array2 = array1.slice().reverse();
var spaces2 = [];
for (var i = 0; i < array1.length; i++) {
if(array2[i] == " ") {
spaces2.push(i);
}
}
console.log(spaces2);
for (var i = spaces2.length - 1; i >=0; i--) {
array2.splice(spaces2[i], 1);
}
console.log(array2);
nWord = array2.join('');
console.log(nWord);
var array3 = [];
for (var i = 0; i < nWord.length; i++) {
array3.push(nWord[i]);
}
console.log(array3);
//for (var i = spaces.length - 1; i >=0; i = i - 1) {
// array3.splice(spaces[i], 0, " ");
//}
for (var i = 0; i < spaces.length; i = i + 1) {
array3.splice(spaces[i], 0, " ");
}
console.log(array3);
var anWord = array3.join('');
return anWord;
}
var input = "We are farmers!";
reverseStr(input);
Reversing a string in JavaScript
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.
How to reverse a string in place without reversing the punctuation?
Another approach is to replace all sequences of letters with their reversed forms using replace and a regular expression, e.g.
function reverseWords(s) {
return s.replace(/[a-z]+/ig, function(w){return w.split('').reverse().join('')});
}
document.write(reverseWords("This is fun, hopefully.")); // sihT si nuf, yllufepoh.
How to reverse a string in javascript?
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>
Reverse a String in JS
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.
function reverseString(str) {
return str.split( '' ).reverse( ).join( '' );
}
Related Topics
Ecmascript 6 Arrow Function That Returns an Object
How to Make the First Letter of a String Uppercase in JavaScript
What Characters Are Valid For JavaScript Variable Names
Is There an "Exists" Function For Jquery
How to Select Text Nodes With Jquery
What Does the Exclamation Mark Do Before the Function
Why Can't I Directly Modify a Component'S State, Really
Why Is the Method Executed Immediately When I Use Settimeout
Wait Until All Jquery Ajax Requests Are Done
Calculate Text Width With JavaScript
Difference Between the '=' and '==' Operators and What Is '==='? (Single, Double, and Triple Equals)
Generate Unique Random Numbers Between 1 and 100
Jquery Event Keypress: Which Key Was Pressed
How to Write Denormalized Data in Firebase