Use js to realize the method of removing the null character at the beginning and end of the string

method 1:

trim(): remove spaces before and after the string

let str = "   123 888 asb  ";
console.log(str);
console.log(str.trim());

The results show that:

 Method 2:

Regular expression: (^\s*) head, (\s*$) tail, use the replace method to replace the first empty string and the tail empty string with

let str = "   123 888 asb  ";
console.log(str);
console.log(str.replace(/(^\s*)|(\s*$)/g, ""));

The results show that:

Method 3:

split converts the string into an array, and the filter condition filter() method is not equal to "", use jion() to convert the array into a string.

The filter() method will create a new array. Each element of the original array is passed into the callback function. The callback function has a return return value, array.filter(function(ele,index,arr), thisValue) the value of the current element of ele (Required) index The index value of the current element. If the return value is true, this element will be saved in the new array; if the return value is false, the element will not be saved in the new array; the original array will not change.

let str = "   123 888 asb  ";
console.log(str);
let newstr = str.split(" ").filter(substr => substr !== "")
console.log(newstr.join(" "));

 The results show that:

Guess you like

Origin blog.csdn.net/qq_64180670/article/details/128279465