Regular Expression + prototype implement trim () function

Source: Internet
Author: User

We know that the string variable in C # has a very useful method trim (). We can use it to remove spaces at the beginning and end of the string. There is no native trim () function in JS, but we can use a regular expression + prototype to implement this function.

 
String. prototype. trim = function () {var Reg =/(^ \ s +) | (\ s + $)/g; return this. replace (Reg ,"");}

Note:

Add the trim method to the prototype of the string constructor so that all strings have this method.

Regular Expressions match the blank characters at both ends of a string (including tabs)

Use the string replace method to replace the blank characters matching the regular expression with the null character "".

InCodeWe can use

 
VaR strtest = 'I am go'; strtest = strtest. Trim (); alert ('prompt information' + strtest + ". ");

If you do not use the trim () function, the following message is displayed: I am a god.

Print when using: the prompt message is "I am a God.


A simple trick, have you learned?

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.