【问题标题】:Regex for checking if a string contains "`" character用于检查字符串是否包含“`”字符的正则表达式
【发布时间】:2020-10-18 12:10:05
【问题描述】:

我正在尝试检查字符串是否包含此字符 `

如果找到该字符,则将该字符串包装在 <div> 之间。

例如:

`this is it

应该变成:

<div>this is it</div>

我已经尝试过,但似乎不起作用:

let arr = "`this is it";
if (arr.includes('`')) {
  arr = arr.replace(/\`(\w+)\`/g, '<div>$1</div>');
}

有什么想法吗?

【问题讨论】:

  • 试试arr.replace(/`([^`]+)`?/g, '&lt;div&gt;$1&lt;/div&gt;')
  • 不相关但不能重新分配const变量
  • \w 等价于[a-zA-Z0-9_],因此与空格不匹配。

标签: javascript html regex string


【解决方案1】:

你可以使用

arr.replace(/`([^`]+)`?/g, '<div>$1</div>')

正则表达式匹配

  • ` - 一个反引号
  • ([^`]+) - 一个或多个除反引号以外的字符
  • `? - 可选的反引号

JavaScript 演示

const arrs = ["`test` is `here`","`this is it"];
const regex = /`([^`]+)`?/g;
for (const arr of arrs) {
  console.log(arr, '=>', arr.replace(regex, '<div>$1</div>'));
}

【讨论】:

    【解决方案2】:

    我认为反引号应该只出现在行首。如果最后还需要,请在正则表达式中的$ 之前添加另一个。

    我还假设您的字符串是多行的,并且任何行都可以以反引号开头。如果不是,请删除 m 标志。

    如果一行中可能有多个反引号分隔的子字符串,请使用 ? 使 * 量词非贪婪,并删除 ^$ 断言。如果这样的子字符串可以跨越多行,还要添加s标志。

    let arr = "`this is it";
    arr = arr.replace(/^`(.+)$/mg, '<div>$1</div>');
    console.log(arr)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-30
      • 2017-05-03
      • 1970-01-01
      • 2021-12-30
      • 1970-01-01
      相关资源
      最近更新 更多