JS Write Trim () function __ Data structure

Source: Internet
Author: User
Tags rtrim

There is no trim function in the 1.js itself, but you can write a
function Trim (str) {
var newstr = str.replace (/^\s*$/g, "")
Retrun Newstr;

2. Remove the space at both ends of the string, in VBScript you can easily use trim, LTrim, or RTrim, but in JS there is no such 3 built-in methods, need to hand-write. 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 ();)

<script language= "javascript"
String.prototype.trim=function () {
    return this.re Place (/(^\s*) | ( \s*$)/g, "");   
String.prototype.ltrim=function () {
    return This.replace (/(^\s*)/g, "");
String.prototype.rtrim=function () {
    return This.replace (/(\s*$)/g, "");

can be written as a function: (Trim (str))
<script type= "text/javascript"
Function trim (str) { Delete the left and right sides of the space
     return str.replace (/(^\s*) | ( \s*$)/g, "");   
Function LTrim (str) {//delete left space
     return str.replace (/(^\s*)/g, "");
function RTrim (str) {//delete the right space
     return str.replace (/(\s*$)/g, "");

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.