There are three ways to remove whitespace from a string using js
(1) Replace matching method
Remove all Spaces in the string: STR =str.replace(/\s*/g,””); Remove two Spaces: the ends of the string STR = STR. Replace (/ ^ | \ \ s * * $s/g, “”);
Remove left Spaces from string: STR = str.replace(/^\s*/,””); Remove Spaces on the right side of the string: STR = str.replace(/(\s*$)/g,””);
var str = "j a v a S cr ipt "; var str1=str.replace(/\s*/g,""); console.log(str); //j a v a S cr ipt console.log(str1); //javaScriptCopy the code
The above code removes all Spaces from STR
var str = " j a v a S cr ipt "; var str1=str.replace(/^\s*|\s*$/g,""); console.log(str); // j a v a S cr ipt console.log(str1); //j a v a S cr iptCopy the code
The above code shows the removal of Spaces around STR
var str =" j a v a S cr ipt " var str1=str.replace(/^\s*/,""); console.log(str); // j a v a S cr ipt console.log(str1); //j a v a S cr iptCopy the code
The above code removes the space to the left of STR
var str=" j a v a S cr ipt " var str1= str.replace(/(\s*$)/g,""); console.log(str); // j a v a S cr ipt console.log(str1); // j a v a S cr iptCopy the code
The above code removes the space to the right of the STR string
(2)STR. The trim () method
The trim() method is used to remove whitespace from both ends of the string and return it. Trim does not affect the string itself, but returns a new string. Defect: Only Spaces at both ends of a string can be removed, not Spaces in the middle
var str = " w t "; var str_1 = str.trim(); console.log(str_1); // there are no Spaces on the left and right sides of the outputCopy the code
(3)JQ method: $.trim(STR) method
The $.trim() function removes whitespace from both ends of a string.
The $.trim() function removes all newlines, Spaces (including consecutive Spaces), and tabs 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.
var str = " 6 6 "; var str_1 = $.trim(str); console.log(str_1); //6 6// There are no Spaces on the left and right sides of the outputCopy the code