Remove the space between the left and right sides of the string (Implementation code) _javascript tips

Source: Internet
Author: User
In daily work, filtering the special characters in the form is a very common function, such as the text required to enter a simple number, but the user sometimes mistakenly input some extra space or other characters mixed text, which obviously does not meet the input requirements.
Let's learn how to remove the space between the left and right sides of the string.
Before filtration:
  
After filtration:
  
HTML code:
 <div class= "main" >
     <input id= "UserName" type= "text" placeholder= "Please enter username" >
     <input id= "rule" Type= "button" value= "Filter" >
   </div>

CSS code:

html,body,div,input{margin:0;padding:0}
    . main{width:400px;height:auto;padding:0 15px;text-align:center}
    . Main input{width:100%;height:35px;border:none;margin-top:20px;border-radius:5px;}
    Input[type= "text"]{text-align:left;padding-left:15px;box-sizing:border-box;border:1px solid blue;
    Input[type= "button"]{width:50%;background:blue;}
    @media only screen and (max-width:415px) {
      . Main{width:100%;box-sizing:border-box}}
    

JS section:

var userName = document.getElementById (' UserName '),
        rule   = document.getElementById (' rule '),
        Regexempty =/^ (\s|\u00a0) +| (\s|\u00a0) +$/g;

    Rule.onclick = function () {
      username.value = userName.value.replace (Regexempty, ');//replace
      Console.log ( Username.value);
    }

The above text to remove the left and right sides of the space (Implementation code) is a small series to share all the content, I hope to give you a reference, but also hope that we support the cloud habitat community.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.