3

I have a string and I want to replace every capital 'I' with small 'i', and every small 'i' with a capital 'I'. As you can see if I do this in two stages it just converts it, then converts it back to how it was before. So how would I do it all at once?

<html>
<head>
<script type="text/javascript">
function init() {
    text = document.getElementById('test');
    newtext = text.innerHTML.replace(/I/g, "i");
    newtext = newtext.replace(/i/g, "I");
    text.innerHTML = newtext;
}
</script>   
</head>

<body onload="init()">
<div id="test">
THIS IS SOME TEST 
</div>
</body>
</html>
0

1 Answer 1

7
newtext = text.innerHTML.replace(/[iI]/g, function(l) {
  return l.toUpperCase() === l ?
    l.toLowerCase() : l.toUpperCase();
});
Sign up to request clarification or add additional context in comments.

4 Comments

+1, and made a small edit so that it only works on i and I.
to me that sais 'if i is equal to I then return i' which dont make sense but owell it works lol
@AndyLobel, for every character that is either i or I the function will be called. It compares the letter to itself uppercase'd. So, for the letter i, toUpperCase will return I which is not === to i, meaning that the function will return the upper case version, and vice versa for the opposite.
@999 ah right i get it now, is there anything wrong with doing return l == "i" ? "I" : "i";

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.