JavaScript trim 实现去除字符串首尾指定字符的简单方法

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, '');
};

https://www.jb51.net/article/101338.htm

posted @ 2021-06-07 12:01  _迷途  阅读(553)  评论(0编辑  收藏  举报