Forums

  • # February 16, 2017 at 11:21 am

    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

    change 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

    thanks 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

    It will be a little more complicated:

    # February 17, 2017 at 12:18 pm

    thanks again @bearhead ..is it possible to execute without any loop?

    # February 17, 2017 at 12:38 pm

    I 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

    @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 the replace 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

    Update: 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

    yeah, sorry I deleted that pen a few day ago… Mottie’s solution looks better anyway.

Viewing 9 posts - 1 through 9 (of 9 total)

You must be logged in to reply to this topic.

icon-anchoricon-closeicon-emailicon-linkicon-logo-staricon-menuicon-nav-guideicon-searchicon-staricon-tag