Home  >  Article  >  Web Front-end  >  js去空格技巧分别去字符串前后、左右空格_javascript技巧

js去空格技巧分别去字符串前后、左右空格_javascript技巧

WBOY
WBOYOriginal
2016-05-16 17:19:211217browse

分别去字符串前后,左边,右边空格

复制代码 代码如下:

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,"")}

为String对象增加一个trim方法。
以后就可以这样使用:
复制代码 代码如下:

var s = " abc ";
s = s.trim(); // s是个String,可以使用刚定义的trim方法。
alert(s);
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