问题
I need to convert all lower characters to upper and all upper to lower in some string.
For example
var testString = 'heLLoWorld';
Should be
'HEllOwORLD'
after conversion.
What is the most elagant way to implement this, without saving temp string.
I would be much more better if achieve such result using regular expressions.
Thanks.
回答1:
Here's a regular expression solution, which takes advantage of the fact that upper and lowercase letters differ by the bit corresponding to decimal 32:
var testString = 'heLLo World 123',
output;
output= testString.replace(/([a-zA-Z])/g, function(a) {
return String.fromCharCode(a.charCodeAt() ^ 32);
})
document.body.innerHTML= output;
回答2:
Here is one idea:
function flipCase(str) {
return str.split('').reduce(function(str, char) {
return str + (char.toLowerCase() === char
? char.toUpperCase()
: char.toLowerCase());
}, '');
}
回答3:
Here is an idea with RegEx
var testString = 'heLLoWorld';
var newString = '';
for(var i =0; i< testString.length; i++){
if(/^[A-Z]/.test(testString[i])){
newString+= testString[i].toLowerCase();
} else {
newString+= testString[i].toUpperCase();
}
}
working exaple here http://jsfiddle.net/39khs/1413/
回答4:
testString.split('').map(function(c) {
var f = 'toUpperCase';
if(c === c.toUpperCase()) {f = 'toLowerCase';}
return c[f]();
}).join('');
来源:https://stackoverflow.com/questions/33851330/convert-upper-chars-to-lower-and-lower-to-upper-vice-versa