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(" ");
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
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!$"));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With