去掉字符串之间的空格(trim)
var str = ' ab c d e ' // 去掉字符串所有空格 console.info(str.replace(/\s+/g,"")) // 去掉首尾空格 console.info(str.replace(/^ +| +$/g,"")) // 去掉首尾空格 console.info(str.trim()) // 自定义方法去掉首尾空格 String.prototype.delejj = function() { return this.replace(/^ +| +$/g,""); } const delekg = (str, pos = 'both') => { if (pos == 'both') { return str.replace(/^\s+|\s+$/g, ""); // 去掉首尾 } else if (pos == "left") { return str.replace(/^\s*/, ''); } else if (pos == 'right') { return str.replace(/(\s*$)/g, ""); } else if (pos == 'all') { return str.replace(/\s+/g, ""); } else { return str; } } console.info('方法',delekg(str,'left')) // note:console输出多个值中间有一个空格 console.info('1','2','3')
note:测试的时候如果用console('1', str.trim(), '3'),误以为是去不掉首尾空格,其实是console自带的空格

浙公网安备 33010602011771号