Five implementation methods for removing spaces before and after strings in js and comparison _ javascript skills

Source: Internet
Author: User
If you enter spaces during registration, how can we remove them? Next, let's share with you the frequently used JavaScript code. For more information, see, we hope this will help you to remove spaces when users enter spaces during project registration?
Below is my frequently used js to share with you:

First: Replacement of cyclic check
[Javascript]

The Code is as follows:


// For the user to call
Function trim (s ){
Return trimRight (trimLeft (s ));
}
// Remove the left blank
Function trimLeft (s ){
If (s = null ){
Return "";
}
Var whitespace = new String ("\ t \ n \ r ");
Var str = new String (s );
If (whitespace. indexOf (str. charAt (0 ))! =-1 ){
Var j = 0, I = str. length;
While (j <I & whitespace. indexOf (str. charAt (j ))! =-1 ){
J ++;
}
Str = str. substring (j, I );
}
Return str;
}
// Remove the blank www.jb51.net on the right.
Function trimRight (s ){
If (s = null) return "";
Var whitespace = new String ("\ t \ n \ r ");
Var str = new String (s );
If (whitespace. indexOf (str. charAt (str. length-1 ))! =-1 ){
Var I = str. length-1;
While (I> = 0 & whitespace. indexOf (str. charAt (I ))! =-1 ){
I --;
}
Str = str. substring (0, I + 1 );
}
Return str;
}


Type 2: Regular Expression replacement
[Javascript]

The Code is as follows:


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.