Home  >  Article  >  Web Front-end  >  How to remove spaces on both sides of a string in nodejs

How to remove spaces on both sides of a string in nodejs

WBOY
WBOYOriginal
2022-01-10 11:40:313453browse

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.

How to remove spaces on both sides of a string in nodejs

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn