如何使用 javascript 获取字符串中匹配模式的索引?
考虑 string original_string = "i am [1@some user] some more text [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 标记中,并将它们放入原始字符串中。
有人可以帮我解决这个问题吗?谢谢。
最佳答案
如果你想替换[id@name]
带有格式化名称的部分(例如 <span>name</span>
),您可以使用 String.replace。
const text = 'i am [1@some user] some more text [2@another user]';
text.replace(/\[\d+@([A-z\s]*)\]/g, '<span>$1</span>');
// outputs: i am <span>some user</span> some more text <span>another user</span>
String.replace
支持在 newSubstr
中使用捕获组参数(新子串)。
关于javascript - 如何使用javascript获取字符串中的匹配索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57792618/