The task says : Change the order of words in a sentence but let non-alphanumerical characters stay in the same place e.g: 'Hello, it is world here.' -> "here, world is it Hello."
So far i have created something like this, but i need to optimize it (there are too many loops).
var text = 'Hello, it is world here.';
function reverseFunc(text){
let alpha = text.match(/[a-z0-9]+/gi).reverse();
let nonAlpha = text.match(/[\W_]+/gi);
let result = [];
console.log("Alpha : " + alpha)
console.log("Non alpha : " +nonAlpha)
if(alpha == null || nonAlpha == null) console.log(text)
else if((/[a-z0-9]/i).test(text.split("")[0])){
if (alpha.length == nonAlpha.length) {
for (let i = 0; i < nonAlpha.length; i++) {
result.push(alpha[i], nonAlpha[i]);
}
console.log(result.join(""))
return(result.join(""))
}else{
for (let i = 0; i < alpha.length; i++) {
result.push(alpha[i], nonAlpha[i]);
}
console.log(result.join(""))
return(result.join(""))
}
}else{
if (nonAlpha.length == alpha.length) {
for (let i = 0; i < alpha.length; i++) {
result.push(nonAlpha[i], alpha[i]);
}
console.log(result.join(""))
return(result.join(""))
}else{
for (let i = 0; i < nonAlpha.length; i++) {
result.push(nonAlpha[i], alpha[i]);
}
console.log(result.join(""))
return(result.join(""))
}
}
}
reverseFunc(text)
I also have a problem when the text is only 1 char long e.g ".", or " ". I tried this:
if(alpha == null || nonAlpha == null) console.log(text)
but it seems like it is working only for alphanumeric chars.How could this algorithm be corrected?