Five ways Javascript removes whitespace before and after a string

Source: Internet
Author: User

First: cyclic check replacement
[JavaScript]

 function  return

Remove the left blank

functionTrimleft (s) {if(s = =NULL) { return""; } varwhitespace =NewString ("\t\n\r"); varstr =NewString (s);if(Whitespace.indexof (Str.charat (0))! =-1) { varj=0, i =str.length; while(J < i && Whitespace.indexof (Str.charat (j))! =-1) {J++; } STR=Str.substring (J, i);} returnstr;} 

Remove the blank on the right

functionTrimRight (s) {if(s = =NULL)return""; varwhitespace =NewString ("\t\n\r"); varstr =NewString (s);if(Whitespace.indexof (Str.charat (str.length-1))! =-1){ vari = Str.length-1;  while(I >= 0 && whitespace.indexof (str.charat (i))! =-1) {i--; } STR= str.substring (0, i+1); } returnstr;} 

The second type: regular replacement
[JavaScript]

 <script language= "JavaScript" > <!-- String.prototype.Trim  = Span style= "color: #0000ff;" >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> 

The third type: using jquery

[JavaScript]

$.trim (str) jquery internal implementation is: [JavaScript] function  return str.replace (/^ (\s|\u00a0) +/, "). Replace (/(\S|\U00A0) +$/, '

Fourth: Use of Motools

[JavaScript]

functionreturn str.replace (/^ (\s|\xa0) +| ( \S|\XA0) +$/g, "

Fifth: Clipping string mode
[JavaScript]

function= str.replace (/^ (\s|\u00a0) +/, 'for (var i=str.length-1; i>=0; i--if(/\s/= str.substring (0, i+1breakreturn str;}

Five ways Javascript removes whitespace before and after a string

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.