Convert upper chars to lower and lower to upper (vice versa) [duplicate]

北慕城南 提交于 2019-12-08 17:58:26

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!