7

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.

  • As JavaScript strings are immutable this is technically impossible, you have to end up with at least one additional string (which you can of course assign back to `testString`, but the additional string was still there.) All of the answers so far end up with copies of the string, 2 with two copies (one in an array and one in a string in one case, both in arrays in the second), one with an explicit copy in a second string. – blm Nov 22 '15 at 04:01
  • See [this demo](https://jsfiddle.net/q6rqy2bp/) based on the original question answer. – Wiktor Stribiżew Nov 22 '15 at 10:17

4 Answers4

3

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;
Rick Hitchcock
  • 35,202
  • 5
  • 48
  • 79
2

Here is one idea:

function flipCase(str) {
  return str.split('').reduce(function(str, char) {
    return str + (char.toLowerCase() === char
      ? char.toUpperCase()
      : char.toLowerCase());
  }, '');
}
Hunan Rostomyan
  • 2,176
  • 2
  • 22
  • 31
1

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/

nestedl00p
  • 490
  • 3
  • 14
  • Something like str.replace(/./g, function(c) { return case-modified or original c; }) is arguably more elegant, which is a request in the question. – blm Nov 22 '15 at 04:03
  • Also, the above will fail for uppercase but non-ASCII characters, for example 'Å' stays the same but should turn into 'å'. – blm Nov 22 '15 at 04:12
  • It was only an idea, I don't have a lot of experience with JS, but I am looking into your suggestions, thanks. – nestedl00p Nov 22 '15 at 04:31
0
testString.split('').map(function(c) {
  var f = 'toUpperCase';
  if(c === c.toUpperCase()) {f = 'toLowerCase';}
  return c[f]();
}).join('');