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

React JS中如何去除字符串首尾的双引号

React JS 字符串首尾双引号去除方案

下面提供两种可直接落地的实现方式,适配不同场景:

1. 正则替换法(适配不确定首尾是否一定带双引号的场景)

该方案只会删除字符串首尾的双引号,不会影响字符串中间的双引号内容:

// 示例字符串,首尾带双引号
const originStr = "\"item.countryId ===3 && item.examId ===2 && item.streamId.includes(3) && item.createdName ===manoj \"";
// 仅删除首尾双引号
const handledStr = originStr.replace(/^"|"$/g, '');

// 如果需要同时清除首尾双引号外的多余空白,使用如下正则
const handledStrWithTrim = originStr.replace(/^\s*"|"\s*$/g, '');

2. 截取法(性能更高,适配明确首尾为双引号的场景)

先做类型和首尾字符判断,避免误删正常字符,性能优于正则匹配:

const originStr = "\"item.countryId ===3 && item.examId ===2 && item.streamId.includes(3) && item.createdName ===manoj \"";
let handledStr = originStr;
if (typeof originStr === 'string' && originStr.startsWith('"') && originStr.endsWith('"')) {
  handledStr = originStr.slice(1, -1);
}

如果以上方案不生效,可先打印查看原始字符串的实际格式,排查是否存在转义双引号(\")的情况,若存在转义字符将正则规则调整为/^\\"|\\"$/g即可。

内容的提问来源于stack exchange,提问作者Sai Manoj v

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 00:57:03