You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 08:16:02