I wrote a function in js to remove the beginning and end spaces and specific characters. The code is as follows:
The code copy is as follows:
function trim(str, charlist) {
return str.replace(new RegExp('^[//s'+charlist+']+|[//s'+charlist+']+$', 'g'), '');
}
The code looks like nothing wrong, and there are no errors when running.
Until today, when I searched for "note3" in the search bar, I found that the content searched in the address bar became "ote3", and other letters or numbers started with normal beginnings. What is the search, what is the content in the address bar.
After debugging the code, change the code to:
The code copy is as follows:
function trim(str, charlist) {
var charlist = charlist || "";
return str.replace(new RegExp('^[//s'+charlist+']+|[//s'+charlist+']+$', 'g'), '');
}
Added initialization of charlist to the function. Search for "note3" this time and the result is correct.
Although js is a weak-type language, using variables does not require initialization. When running, the code will automatically convert and assign values. However, doing so will cause some unexpected problems, so it is very necessary to initialize all used variables.
That’s all for today, I hope you can like it.