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)