Home > Article > Web Front-end > How to remove spaces on both sides of a string in nodejs
In nodejs, you can use the replace method and regular expressions to remove spaces on both sides of a string. The syntax is "str.replace(/(^\s*)|(\s*$)/g, " ");" The replace() method is used to replace characters in a string, or to replace a substring that matches a regular expression.
The operating environment of this tutorial: windows10 system, nodejs version 12.19.0, DELL G3 computer.
How to remove spaces on both sides of a string in nodejs
To remove spaces on the left and right ends of a string, you can easily use trim, ltrim or rtrim, but there are no these three built-in methods in js and need to be written manually. The following implementation method uses regular expressions, which is very efficient, and adds these three methods to the built-in methods of the String object.
The method format written as a class is as follows: (str.trim();)
<script language="javascript"> String.prototype.trim=function(){ return this.replace(/(^\s*)|(\s*$)/g, ""); } String.prototype.ltrim=function(){ return this.replace(/(^\s*)/g,""); } String.prototype.rtrim=function(){ return this.replace(/(\s*$)/g,""); } </script> 写成函数可以这样:(trim(str)) <script type="text/javascript"> 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,""); } </script>
For more node-related knowledge, please visit: nodejs tutorial! !
The above is the detailed content of How to remove spaces on both sides of a string in nodejs. For more information, please follow other related articles on the PHP Chinese website!