Home › Forums › JavaScript › convert uppercase to lowercase and vice-versa
- This topic is empty.
-
AuthorPosts
-
February 16, 2017 at 11:21 am #251581PranabParticipant
here’s the link – https://jsfiddle.net/vLmqd35v/
<input type="text"/> <p></p> var inp = document.querySelector("input"); inp.addEventListener("input", text); function text(){ var p = document.querySelector("p"); var s = inp.value; if(!s.match(/A-Z/i)) p.innerHTML = s.toUpperCase(); else p.innerHTML = s.toLowerCase; }
this is convert lower to upper..but how to convert upper to lower?
February 16, 2017 at 12:58 pm #251586bearheadParticipantchange
function text()
to:function text(){ var p = document.querySelector("p"); var s = inp.value; if(!s.match(/a-z/i)) p.innerHTML = s.toLowerCase(); else p.innerHTML = s.toUpperCase; }
Basically just invert what the original function was doing…
February 16, 2017 at 1:10 pm #251587PranabParticipantthanks for the answer @bearhead ..now, how do execute both in text function..i mean when i input some value in text field..it will automatically convert upper to lower and lower to upper..
February 16, 2017 at 1:36 pm #251589bearheadParticipantIt will be a little more complicated:
http://codepen.io/kvana/pen/egoKXbFebruary 17, 2017 at 12:18 pm #251636February 17, 2017 at 12:38 pm #251637bearheadParticipantI doubt it, the function needs to loop through the input’s value every time it changes… Why don’t you want to have a loop in the script?
March 18, 2017 at 12:44 pm #252909MottieMember@bearhead The embedded codepen doesn’t appear to be available anymore. Would you please paste the code into the answer?
@Pranab If you don’t want a loop, use thereplace
function instead:https://jsfiddle.net/Mottie/vLmqd35v/1/
var inp = document.querySelector("input"); inp.addEventListener("input", text); function text(){ var p = document.querySelector("p"); var s = inp.value.trim(); var lc = /[a-z]/; p.innerHTML = s.replace(/./g, function(v){ return lc.test(v) ? v.toUpperCase() : v.toLowerCase(); }); }
March 18, 2017 at 12:59 pm #252910MottieMemberUpdate: There is a limitation of the above code… lower-case letters with diacritics will not be modified. You would need to include all lower case unicode characters, which isn’t as simple as it sounds because you can’t add a simple range into the regular expression because upper & lower case letters alternate (ref).
Here is a demo that includes a lesser subset of diacritics which only requires the change of this line:
var lc = /[a-zàèìòùáéíóúýâêîôûãñõäëïöüÿçßøåæœ]/;
March 20, 2017 at 6:58 am #252960bearheadParticipantyeah, sorry I deleted that pen a few day ago… Mottie’s solution looks better anyway.
-
AuthorPosts
- The forum ‘JavaScript’ is closed to new topics and replies.