javascript - 如何使用正则表达式和 javascript 将模式替换为 span 元素?

标签 javascript regex

您好,我想在字符串中搜索模式,从匹配的模式中提取一个值并将其放入 span 标记中,我该怎么做?

考虑字符串

“我是[1@某个用户]更多文字[2@另一个用户]”

我想匹配方括号中的字符串

[1@some user] [2@another user] and extract the string after @ 

所以应该是“某个用户”“另一个用户”

之后我想构建一个像这样的字符串

“我是<span>some user</span>更多文字<span>another user</span>

我尝试使用下面的代码,

replace = (str) => {
    const pattern = /\[\d+@(?<name>[^\]\r\n]*)]/g;
    const matched_names = str.matchAll(pattern);
    let names = [];
    for (const match of matched_names) {
        names.push(match.groups.name);
    }
    return str.split(pattern).map((string) => {
        if (names.indexOf(string) >= 0) return <span>{string}</span>;
        return string;
    });
 }

上面的代码片段可以工作,但如果字符串是“i am [3@some user]someuser”则失败

如果名称与方括号中的名称相同并且 [3@someuser]someuser 之间没有空格,则基本上会失败

我该如何解决这个问题。有人可以帮我解决这个问题吗?谢谢。

最佳答案

这应该可以做到:

\[\d+@(.*?)\]

$1将包含所需的用户名。

https://regex101.com/r/Rv31AC/4

const regex = /\[\d+@(.*?)\]/g;
const str = `i am [1@some user] more text [2@another user]
[1@some user] [2@another user] and extract the string after @ 
i am [3@some user]someuser`;
const subst = `<span>$1</span>`;

// The substituted value will be contained in the result variable
const result = str.replace(regex, subst);

console.log(result);

关于javascript - 如何使用正则表达式和 javascript 将模式替换为 span 元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57788796/

相关文章:

regex - 正则表达式插入缺失的字符串?

regex - 具有正则表达式循环值的 shell 脚本输入字符串

javascript - 如何在 JavaScript 中检查变量是否为整数?

javascript - 这些看似相似的JS代码有什么区别?

javascript - 如何使用多个setInterval()?

java - 按字母和数字拆分字符串

python - 使用perl或python将阿拉伯字符 "ا"替换为一个单词中的 "a",但替换为另一个单词中的 "ә"

regex - 查找最里面的大括号中以给定子字符串的单词开头的文本

javascript - 控制台 HighCharts 错误破坏了可视化

javascript - 如果未使用 Protractor 选择,请选择复选框