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

VueJS如何去除用户提交字符串首尾引号且不影响内部引号内容

实现方案

你可以通过以下两种安全的方式仅移除字符串首尾的引号,不会修改内部文本内容:


方案1:字符截取法(更稳妥,无正则匹配误差)

先判断字符串首尾是否为单/双引号,匹配成功后再截取中间内容,兼容性更高:

// 定义通用移除首尾引号工具函数
const trimSurroundQuotes = (str) => {
  if (typeof str !== 'string') return str
  const hasWrapQuote = (str.startsWith("'") && str.endsWith("'")) || (str.startsWith('"') && str.endsWith('"'))
  return hasWrapQuote ? str.slice(1, -1) : str
}

在你的代码中直接调用即可:

data() {
    return {
        entryNotes: trimSurroundQuotes(this.post.entryNotes)
    }
}

方案2:正则匹配法(写法更简洁)

使用正则仅匹配首尾位置的单/双引号,直接替换移除:

data() {
    return {
        entryNotes: this.post.entryNotes.replace(/^['"](.*)['"]$/s, '$1')
    }
}

正则说明:

  • ^['"] 匹配字符串开头的第一个单/双引号
  • (.*) 捕获中间所有内容(含内部引号)
  • ['"]$ 匹配字符串末尾的最后一个单/双引号
  • s 修饰符支持匹配换行符,兼容textarea的多行文本场景

动态数据适配

如果this.post.entryNotes是会动态更新的异步数据,建议将entryNotes改为计算属性,实现自动同步处理:

computed: {
  entryNotes() {
    return typeof this.post.entryNotes === 'string' 
      ? this.post.entryNotes.replace(/^['"](.*)['"]$/s, '$1') 
      : this.post.entryNotes
  }
}

以上两种方案都符合你的需求,示例输入'Hello World, welcome to "fooWorld!"'经过处理后会得到预期输出Hello World, welcome to "fooWorld!"。

内容的提问来源于stack exchange,提问作者fooman

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 15:24:00