If your project is using the jQuery framework, to remove the null characters at the beginning and end of the string, you will of course choose: jQuery.trim(string). How to implement it simply without using jQuery. I have previously posted a small code snippet: Javascript removes spaces around a string - trim(). This is relatively crudely written and requires recursive operations. So many people are very dissatisfied with the quality of the code, including me.
Occasionally I looked at the jQuery code and found that it is very worth learning.
Let’s see how it implements this function. There is only one sentence in the code: use the regular method.
JavaScript Trim implementation code
function trim(text) {
return (text || "").replace(/^/s |/s $ /g, "");
}
If you do not use jQuery or other frameworks in your project, you can copy this code to use this function. I believe you will be satisfied with the structure and quality of the code.