Home > Article > Web Front-end > Use js custom trim function to remove spaces at both ends
This article mainly introduces the function of deleting spaces at both ends of a string using the js custom trim function, and analyzes the related operation skills of javascript based on regular replacement to implement a similar trim function to delete spaces at both ends of a string, combined with examples, and comes with jQuery similar functions. For how to use the function, friends who need it can refer to
This article describes the example of js custom trim function to achieve the function of deleting spaces at both ends. Share it with everyone for your reference, the details are as follows:
Compatible with IE lower version browsers, and some other lower version script browsers
There is no trim function in js
//删除左右两端的空格 function trim(str){ return str.replace(/(^\s*)|(\s*$)/g, ""); } //删除左边的空格 function ltrim(str){ return str.replace(/(^\s*)/g,""); } //删除右边的空格 function rtrim(str){ return str.replace(/(\s*$)/g,""); }
Or extend the String type attribute
String.prototype.trim = function() { return this.replace(/(^\s*)|(\s*$)/g, ""); } var str = document.getElementById("test").value; alert( str.trim() );
Or simply give up using js and use jQuer’s$.trim(str )
var str = $("#test").val(); alert( $.trim(str) );
The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.
Related articles:
How to implement a static server using Node.js
Comparison of map, set, array, and object in ES6 ( Detailed tutorial)
How to implement change detection using Angular
The above is the detailed content of Use js custom trim function to remove spaces at both ends. For more information, please follow other related articles on the PHP Chinese website!