JSFiddle - React, Tailwind, and code Playground
by kpulkit29
JavaScript
//Hello, World
//olleH, dlroW!
/* split by space
regex to check whther its between [a-zA-Z] */
//calculate theb length
//take a new string
// prepend olleh + ,
/* ["Hello,","World!"] */
function reverseWords(sentence) {
let reversedAns = "";
let word = "";
let unmatchedWord = "";
function reset() {
word = "";
unmatchedWord = "";
}
function inAlphabetRange(alpha) {
if(("a"<=alpha && alpha<="z") || ("A"<=alpha && alpha<="Z")) {
return true;
}
return false
}
for(let i=0; i<sentence.length; i++) {
//range
let alpha = sentence[i];
if(alpha == " " || i ===sentence.length-1) {
if(inAlphabetRange(alpha)) {
word = alpha + word;
} else {
unmatchedWord += alpha;
}
reversedAns += word + unmatchedWord;
reset();
}
else if(inAlphabetRange(alpha)) {
/* console.log("here", alpha) */
word = alpha + word;
} else {
unmatchedWord += alpha;
}
}
return reversedAns;
}
console.log(reverseWords("Hello, sdsdsdsd World!"));