JavaScript是否有支持指定待移除字符/字符串的trim方法?
原生JavaScript内置的String.prototype.trim()仅支持移除字符串首尾的空白字符,不支持传入参数指定要移除的字符/子串。你可以通过以下两种方案实现需求:
方案1:自行实现工具函数
根据你的使用场景,可选择对应实现:
场景A:移除首尾所有属于指定字符集合的字符
适用于要移除的是零散字符的场景,匹配你给出的x、z示例效果:
function trimChars(str, charsToTrim) { // 转义正则特殊字符避免语法错误 const escapedChars = charsToTrim.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); return str.replace(new RegExp(`^[${escapedChars}]+|[${escapedChars}]+$`, 'g'), ''); } // 测试 const x = '@@@hello world@@'; console.log(trimChars(x, '@')); // 输出 'hello world' const z = '@@hello@world@@'; console.log(trimChars(z, '@')); // 输出 'hello@world'
场景B:移除首尾连续重复的指定完整子串
适用于要匹配完整子串移除的场景,匹配你给出的y示例效果:
function trimSubstring(str, subStrToTrim) { if (!subStrToTrim) return str; const escapedSub = subStrToTrim.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); return str.replace(new RegExp(`^(?:${escapedSub})+|(?:${escapedSub})+$`, 'g'), ''); } // 测试 const y = 'hellohellohelloworld'; console.log(trimSubstring(y, 'hello')); // 输出 'world'
方案2:使用成熟工具库的现有API
如果你的项目中已经引入了lodash,可直接使用其内置的_.trim方法,该方法天然支持第二个参数指定要移除的字符集合,经过生产环境验证性能优异:
const x = '@@@hello world@@'; console.log(_.trim(x, '@')); // 输出 'hello world'
内容的提问来源于stack exchange,提问作者Siriusmart
相关产品推荐
相关产品推荐

