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

4

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.

Warfield answered 22/11, 2015 at 3:36 Comment(2)
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.Danziger
See this demo based on the original question answer.Reuven
C
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;
Cooper answered 22/11, 2015 at 4:13 Comment(2)
elegant solution for ASCII- / basic alphabet strings, but does not work for unicode characters: "Ć".toLowerCase() == "ć" but String.fromCharCode("Ć" ^ 32) != "ć"Mercaptide
Yes, life was much simpler in the ASCII 8-bit days.Cooper
T
2

Here is one idea:

function flipCase(str) {
  return str.split('').reduce(function(str, char) {
    return str + (char.toLowerCase() === char
      ? char.toUpperCase()
      : char.toLowerCase());
  }, '');
}
Tenace answered 22/11, 2015 at 3:41 Comment(0)
M
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/

Maggiore answered 22/11, 2015 at 3:48 Comment(3)
Something like str.replace(/./g, function(c) { return case-modified or original c; }) is arguably more elegant, which is a request in the question.Danziger
Also, the above will fail for uppercase but non-ASCII characters, for example 'Å' stays the same but should turn into 'å'.Danziger
It was only an idea, I don't have a lot of experience with JS, but I am looking into your suggestions, thanks.Maggiore
W
0
testString.split('').map(function(c) {
  var f = 'toUpperCase';
  if(c === c.toUpperCase()) {f = 'toLowerCase';}
  return c[f]();
}).join('');
Weingarten answered 22/11, 2015 at 3:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.