Answer: I can loop through the string and concatenate letters to a new string
function reverse(str){
var rtnStr = '';
for(var i = str.length-1; i>=0;i--){
rtnStr +=str[i];
}
return rtnStr;
}
reverse('you are a nice dude');
= "edud ecin a era uoy"
How would you reverse words in a sentence?
Answer: You have to check for white space and walk through the string. Ask is there could be multiple whitespace.
//have a tailing white space
//fix this later
//now i m sleepy
function reverseWords(str){
var rev = [],
wordLen = 0;
for(var i = str.length-1; i>=0; i--){
if(str[i]==' ' || i==0){
rev.push(str.substr(i,wordLen+1));
wordLen = 0;
}
else
wordLen++;
}
return rev.join(' ');
}
How would you reverse a string in JavaScript?
Answer: I can loop through the string and concatenate letters to a new string function reverse(str){ var rtnStr = ''; for(var i = str.length-1; i>=0;i--){ rtnStr +=str[i]; } return rtnStr; }
How would you reverse words in a sentence?
Answer: You have to check for white space and walk through the string. Ask is there could be multiple whitespace.
//have a tailing white space //fix this later //now i m sleepy function reverseWords(str){ var rev = [], wordLen = 0; for(var i = str.length-1; i>=0; i--){ if(str[i]==' ' || i==0){ rev.push(str.substr(i,wordLen+1)); wordLen = 0; } else wordLen++; } return rev.join(' '); }