【问题标题】:Javascript: Find all mentions in a string manipulate them and replace themJavascript:查找字符串中的所有提及操作并替换它们
【发布时间】:2019-01-16 01:28:17
【问题描述】:

我想在评论中找到所有出现的@mention 并将它们替换为不同的格式。

我有这个正则表达式可以对所有匹配项进行分组,但所有这些我都必须为 Jira ([~string]) 操作这些字符串,并将它们重新插入到原始字符串中。

comment.match(/[ ]@[^\s]+/g);

有没有更好的办法?

评论输入:

guiyjhk @test hgjhgjh test@this_is.test2 jhgjhgjh @this_is.test2

这是我想要返回的:

guiyjhk [~test] hgjhgjh test@this_is.test2 jhgjhgjh [~this_is.test2]

【问题讨论】:

标签: javascript regex


【解决方案1】:

您可以捕获零次或多次空格或断言组 1 中字符串的开头,匹配 @ 然后在组中捕获而不是空格 \S+

(^|\s+)@(\S+)

然后在替换使用组1和2$1[~$2]

const strings = [
  "guiyjhk @test hgjhgjh test@this_is.test2 jhgjhgjh @this_is.test2",
  "@test"
];
strings.forEach((s) => {
  console.log(s.replace(/@(\S+)/g, "[~$1]"));
});

【讨论】:

    【解决方案2】:

    您可以使用正则表达式匹配捕获@ 之后的部分和之前的空格,然后使用replace() 替换这些匹配项。这将允许您匹配被空格包围的@mention,同时避免test@this_is.test2

    let comment = "guiyjhk @test hgjhgjh test@this_is.test2 jhgjhgjh @this_is.test2"
    
    // catch space then @ then non-space replace with space(s)[non-space]
    comment = comment.replace(/([\s+])@([^\s]+)/g, "$1[~$2]");
    console.log(comment)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-20
      • 1970-01-01
      • 2012-02-07
      • 2021-10-16
      • 1970-01-01
      • 2016-09-26
      相关资源
      最近更新 更多