您好,我想在字符串中搜索模式,从匹配的模式中提取一个值并将其放入 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/