JS去掉字符串中空格

来源:互联网 发布:平面设计笔记本 知乎 编辑:程序博客网 时间:2024/05/22 18:38

1.去掉首尾两头的空格,只能去掉一个空格,不支持多空格的去掉:

if (!String.prototype.trim) {String.prototype.trim = function () {return this.replace(/^\s*([\S]*?)\s*$/g, "$1");}}

2.去掉左边的全部空格

//去除字符串左侧空格String.prototype.LTrim = function() {    return this.replace(/(^\s*)/g, ""); }


3.去掉右边的全部空格

//去除字符串右侧空格String.prototype.RTrim = function() {    return this.replace(/(\s*$)/g, ""); }

4.去掉中间空格

//去除字符串中间空格String.prototype.Trim = function() {    return this.replace(/(^\s*)|(\s*$)/g, ""); }


原创粉丝点击