Home>Article>Web Front-end> How to remove whitespace in javascript
Javascript method to remove whitespace characters: 1. Use the replace regular matching method to remove spaces in the string; 2. Use the "str.trim()" method to delete whitespace characters at both ends of the string; 3. Use " $.trim(str)" method removes whitespace characters at both ends of the string.
The operating environment of this article: windows7 system, javascript version 1.8.5, Dell G3 computer.
js removes spaces (blank characters) from strings
Use js to remove spaces from strings. There are three methods:
1. Regular matching method
Remove all spaces in the string: str = str.replace(/\s*/g,"");
Remove spaces at both ends of the string: str = str.replace(/^\s*|\s*$/g,"");
Remove the spaces on the left side of the string: str = str.replace(/^\s*/ ,"");
Remove the spaces on the right side of the string: str = str.replace(/(\s*$)/g,"");
Example:
var str = " 6 6 "; var str_1 = str.replace(/\s*/g,""); console.log(str_1); //66 var str = " 6 6 "; var str_1 = str.replace(/^\s*|\s*$/g,""); console.log(str_1); //6 6//输出左右侧均无空格 var str = " 6 6 "; var str_1 = str.replace(/^\s*/,""); console.log(str_1); //6 6 //输出右侧有空格左侧无空格 var str = " 6 6 "; var str_1 = str.replace(/(\s*$)/g,""); console.log(str_1); // 6 6//输出左侧有空格右侧无空格
2. str.trim() method
The trim() method is used to delete the blank characters at both ends of the string and return it. The trim method does not affect the original characters. The string itself, it returns a new string.
Defect: Only the spaces at both ends of the string can be removed, but the spaces in the middle cannot be removed
Example:
var str = " 6 6 "; var str_1 = str.trim(); console.log(str_1); //6 6//输出左右侧均无空格
To remove the left space alone, use str.trimLeft(); //var str_1 = str.trimLeft();
To remove spaces on the right side alone, use 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 will remove all newline characters, spaces (including consecutive spaces) and tab characters at the beginning and end of the string. If these whitespace characters are in the middle of the string, they are retained and not removed.
Example:
var str = " 6 6 "; var str_1 = $.trim(str); console.log(str_1); //6 6//输出左右侧均无空格
[Recommended learning:javascript advanced tutorial]
The above is the detailed content of How to remove whitespace in javascript. For more information, please follow other related articles on the PHP Chinese website!