Home >Web Front-end >JS Tutorial >javascript 去掉字符串左边或右边空格

javascript 去掉字符串左边或右边空格

WBOY
WBOYOriginal
2016-06-01 09:54:281753browse

本文章向大家介绍js中删除左右字符串两段的空格。具体代码如下:

1.删除字符串左边的空格

<code class="language-javascript">function leftTrim(str) {  
  if (str.charAt(0) == " ") {  
    str = str.slice(1);  
    str = leftTrim(str);  
  }  
    
  return str;  
}  </code>

 

2.删除字符串右边的空格

<code class="language-javascript">function rightTrim(str) {  
  if (str.length - 1 >= 0 && str.charAt(str.length - 1) == " ") {  
    str = str.slice(0, str.length - 1);  
    str = rightTrim(str);  
  }  
    
  return str;  
} </code>

 

如果需要同事删除字符串两段的空格,直接将两个函数结合起来使用即可。

 

本文章的js/html/php/css代码均可以复制到这个页面进行在线调试,你不妨试一下。

http://www.manongjc.com/runcode

 

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