Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reversing string without affecting any special characters

I want to reverse string

"My! name.is@rin"

My output must be

"yM!  eman.si@nir"

I wrote following code which gives output as "yM eman si nir" Please resolve the issue :

return str = stringIn.split("").reverse().join("").split(/[^a-zA-Z]/g).reverse().join(" ");
like image 818
rkkkk Avatar asked Dec 11 '22 20:12

rkkkk


2 Answers

From your regular expression, it seems your criterion for "special characters" is anything other than the letters A to Z.

You can use String.prototype.replace with a regular expression to match sequences of letters, then provide a replace function that modifies the match before replacing it, e.g.

var stringIn = 'My! name.is@rin';
var rev = stringIn.replace(/[a-z]+/gi, function(s){return s.split('').reverse().join('')});
document.write(rev); // yM! eman.si@nir
like image 91
RobG Avatar answered Dec 13 '22 10:12

RobG


Here is one more approach we can do the same:

function isLetter(char){
    return ( (char >= 'A' &&  char <= 'Z') ||
             (char >= 'a' &&  char <= 'z') );
}    

function reverseSpecialString(string){
    let str = string.split('');
    let i = 0;
    let j = str.length-1;
    while(i<j){
        if(!isLetter(str[i])){
            ++i;
        }
        if(!isLetter(str[j])){
            --j;
        }
        if(isLetter(str[i]) && isLetter(str[j])){
            var tempChar = str[i];
            str[i] = str[j];
            str[j] = tempChar;
            ++i;
            --j;
        }
    }
    return str.join('');
}

document.write(reverseSpecialString("Ab,c,de!$"));
like image 33
ganesh phirke Avatar answered Dec 13 '22 09:12

ganesh phirke