How to reverse a string without affecting the special characters in JavaScript

1 Answer

0 votes
function is_letter(ch) { 
    return ch.length === 1 && ch.match(/[a-z]/i);
} 

String.prototype.replaceAt=function(index, ch) {
    return this.substr(0, index) + ch + this.substr(index + ch.length);
}
 
function reverse(s) { 
    var right = s.length - 1, left = 0; 

    while (left < right) { 
        if (!is_letter(s[left])) 
            left++; 
        else if (!is_letter(s[right])) 
                right--; 
             else { 
                var tmp = s[left];
                s = s.replaceAt(left, s[right]);
                s = s.replaceAt(right, tmp);
                left++; 
                right--; 
             } 
    } 
    return s;
} 
   
s = "a#b$%c&*(def!"; 

s = reverse(s); 

document.write(s);  
 


/*
run:
    
f#e$%d&*(cba! 
    
*/

 



answered Jun 20, 2019 by avibootz

Related questions

...