JavaScript中去除字符串首尾指定字符序列(不区分大小写)的纯JS实现
实现JavaScript字符串首尾特定短语的去除(支持大小写不敏感)
核心实现代码
我们可以通过扩展String.prototype添加自定义的trimPhrase方法,结合正则表达式实现需求,同时处理正则特殊字符的转义,支持大小写不敏感匹配:
// 转义正则特殊字符的工具函数 function escapeRegExp(string) { return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); } // 扩展String原型,添加trimPhrase方法 String.prototype.trimPhrase = function(phrase, caseInsensitive = true) { const escapedPhrase = escapeRegExp(phrase); const flags = caseInsensitive ? 'i' : ''; // 先去除开头匹配的短语 let result = this.replace(new RegExp(`^${escapedPhrase}`, flags), ''); // 再去除结尾匹配的短语 result = result.replace(new RegExp(`${escapedPhrase}$`, flags), ''); return result; };
代码说明
- escapeRegExp:将短语中的正则元字符(如
.、*、+等)转义,避免这些字符被当作正则语法解析,确保精确匹配目标短语。 - trimPhrase方法:
- 接收两个参数:
phrase是要去除的目标短语,caseInsensitive控制是否大小写不敏感(默认开启)。 - 分别构建匹配字符串开头和结尾的正则,根据参数添加
i标志实现大小写不敏感。 - 先替换开头的匹配内容,再替换结尾的,返回最终处理后的字符串。
- 接收两个参数:
验证示例
用你提供的测试字符串验证效果:
var str = "This is a test. This is a test." // 结果: " is a test. This is a test." console.log(str.trimPhrase('this')); // 结果: "This is a test. This is a test" console.log(str.trimPhrase('.')); // 结果: "This is a test. This is a test." console.log(str.trimPhrase('is')); // 结果: " " (句子之间的单个空格) console.log(str.trimPhrase('This is a test.'));
所有示例均符合预期效果。
内容的提问来源于stack exchange,提问作者Darren Gates
相关产品推荐
相关产品推荐

