实例如下:
string.prototype.trim = function (char, type) { if (char) { if (type == 'left') { return this.replace(new regexp('^\\'+char+'+', 'g'), ''); } else if (type == 'right') { return this.replace(new regexp('\\'+char+'+$', 'g'), ''); } return this.replace(new regexp('^\\'+char+'+|\\'+char+'+$', 'g'), ''); } return this.replace(/^\s+|\s+$/g, ''); }; // 去除字符串首尾的全部空白 var str = ' ruchee '; console.log('xxx' + str.trim() + 'xxx'); // xxxrucheexxx // 去除字符串左侧空白 str = ' ruchee '; console.log('xxx' + str.trim(' ', 'left') + 'xxx'); // xxxruchee xxx // 去除字符串右侧空白 str = ' ruchee '; console.log('xxx' + str.trim(' ', 'right') + 'xxx'); // xxx rucheexxx // 去除字符串两侧指定字符 str = '/ruchee/'; console.log(str.trim('/')); // ruchee // 去除字符串左侧指定字符 str = '/ruchee/'; console.log(str.trim('/', 'left')); // ruchee/ // 去除字符串右侧指定字符 str = '/ruchee/'; console.log(str.trim('/', 'right')); // /ruchee
以上就是小编为大家带来的javascript trim 实现去除字符串首尾指定字符的简单方法全部内容了,希望大家多多支持移动技术网~
如对本文有疑问, 点击进行留言回复!!
2016年信息安全工程师综合知识第11-15题解析【建群网培信息安全工程师】
网友评论