JS to remove string spaces (whitespace characters)

Source: Internet
Author: User

The following three methods are used to remove spaces within a string using JS:

(1) Replace regular matching method

Remove all spaces within the string: str = str.replace (/\s*/g, "");

Remove spaces in both ends of the string: str = str.replace (/^\s*|\s*$/g, "");

Remove the left space inside the string: str = str.replace (/^\s*/, "");

Remove spaces to the right of the string: str = str.replace (/(\s*$)/g, "");

  Example:

var str = "6 6"; var str_1 = str.replace (/\s*/g, ""//
var str = "6 6"; var str_1 = str.replace (/^\s*|\s*$/g, "");  //6 6//No spaces on both left and right side of output
var str = "6 6"; var str_1 = str.replace (/^\s*/, "");  //6 6//output to the right there are no spaces to the left
var str = "6 6"; var str_1 = str.replace (/(\s*$)/g, ""); 6 6//output There is no space to the right of the left   

(2) Str.trim () method

The trim () method is used to remove white space characters at both ends of a string and to return, and the trim method does not affect the original string itself, it returns a new string.

Flaw: can only remove the space at both ends of the string, cannot remove the middle space

  Example:

var str = "6 6"; var str_1 = Str.trim ()//6 6//no spaces on left and right side of output

The left space is removed separately using str.trimleft (); var str_1 = Str.trimleft ();

The right space is removed separately using str.trimright ();//var str_1 = Str.trimright ();

(3) JQ method: $.trim (str) method

The $.trim () function is used to remove whitespace characters at both ends of a string.

  Note:the $.trim () function removes all line breaks at the beginning and end of the string, spaces (including contiguous spaces), and tabs. If these whitespace characters are in the middle of a string, they will be preserved and will not be removed.

  Example:

var str = "6 6"; var str_1 =//6 6//output no spaces on left and right side

JS to remove string spaces (whitespace characters)

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.