【发布时间】:2020-01-07 14:19:20
【问题描述】:
如何使用 javascript 获取字符串中匹配模式的索引?
考虑 string original_string = "我是 [1@some user] 还有一些文本 [2@another user]"
我正在使用模式 /[\d+@(?[^]\r\n]*)]/g 来匹配方括号中的字符串
然后我使用 string.matchAll(original_string) 来获取匹配项
const matches = string.matchAll(original_string);
let names = [];
for (const match in matches) {
names.push(match);
}
now the names array will contain ["some user", "another user"]
now how do i get the index of the first match in original string from names array.
const final_string = []
const original_string = "i am [12@some user] some text [2@some user2]"
let prev_match_pos = 0
for each match in original_string
final_string.push(text from the end of prev match up until current
match start)
final_string.push(<span>match</span>)
update prev_match_pos
final_string.push(text from the end of previous match to the end of the
original string)
我想在javascript中实现上述算法。
基本上我想转换这个字符串“我是 [1@some user] 还有一些文本 [2@another user]”
到
“我是 <span>some user</span> 更多文字‘另一个用户’”
我该怎么做?
基本实现如下,
获取括号中的字符串。 从括号中的字符串中提取 @ 字符后的值。 然后将提取的值嵌入到 span 标签中,并将它们放在原始字符串中。
有人可以帮我解决这个问题吗?谢谢。
【问题讨论】:
-
请先自己试一试。一旦您尝试过并遇到问题,请在 SO 上发布另一个问题,说明您遇到的具体问题
-
我已经解释了我遇到问题的地方。找到匹配项后,我不知道如何在字符串中替换它们。
标签: javascript