JavaScript _javascript tips for removing whitespace from the left and right ends of a string

Source: Internet
Author: User
Tags rtrim

Remove the space between the left and right sides of the string, you can easily use trim, LTrim, or RTrim in VBScript, but in JS there are no 3 built-in methods that need to be written manually. The following implementation method uses regular expressions and is efficient and adds these three methods to the built-in methods of the string object.

The methods written in the class are as follows: (Str.trim ();)

Copy Code code as follows:

<script language= "JavaScript" >
String.prototype.trim=function () {
Return This.replace (/(^\s*) | ( \s*$)/g, "");
}
String.prototype.ltrim=function () {
Return This.replace (/(^\s*)/g, "");
}
String.prototype.rtrim=function () {
Return This.replace (/(\s*$)/g, "");
}
</script>

This can be written as a function: (Trim (str))

Copy Code code as follows:

<script type= "Text/javascript" >
function Trim (str) {//Remove spaces at left and right ends
Return Str.replace (/(^\s*) | ( \s*$)/g, "");
}
function LTrim (str) {//delete left space
Return Str.replace (/(^\s*)/g, "");
}
function RTrim (str) {//Remove the right space
Return Str.replace (/(\s*$)/g, "");
}
</script>

The above is 2 kinds of JavaScript to remove both sides of the string of space method, I hope you can enjoy.

Related Article

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.