JS Trim () Remove string and trailing blanks

Source: Internet
Author: User

Usually, when the form is validated, the text of the input box needs to be taken out of the string and trailing blanks.

The current version of the browser is natively supported by the trim () method, and the previous version of JQ also implements support for the method.

Boring time can be concerned about how to achieve, sometimes written interview will also ask, by the way review the regular.

  

Remove the end and end spaces + use regular, nothing more than to find the match to the white space character, and then put it/they replace it. Understand the sermon, but there are all roads through Rome.

1. Regular method: Match the first and the trailing blanks separately, then remove

1 function Trim (str) {2     return str.replace (/^\s\s*/, "). Replace (/\s\s*$/,"); 3 }

Version 2.JQ: This regular method of the object is the global str, relative to the first, a little slower, but look good

1 function Trim (str) {2     return str.replace (/^\s+|\s+$/g, ");   3 }

3. Ultimate version: Return to the original idea, just use the regular to remove the first space, find the trailing space, use substring to intercept it, avoid using regular to find a global replacement, improve performance

1 functionTrim (str) {2     varstr = str.replace (/^\s+/, "), I = 0, L =str.length;3      for(; i<len,i++){4         if(/\s/. Test (Str.charat (i))) {5str = str.substring (0, i+1);//or str.substr (0, i);6              Break;7         }8     }9     returnstr;Ten}

Reference book: JavaScript Framework Design-Masaki

JS Trim () Remove string and trailing blanks

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.