Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript - Replace two characters with each other?

Tags:

javascript

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>
like image 690
Andy Lobel Avatar asked Jul 04 '26 04:07

Andy Lobel


1 Answers

newtext = text.innerHTML.replace(/[iI]/g, function(l) {
  return l.toUpperCase() === l ?
    l.toLowerCase() : l.toUpperCase();
});
like image 122
James Avatar answered Jul 07 '26 22:07

James



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!