javascript - 如何使用javascript获取字符串中的匹配索引?

标签 javascript

如何使用 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/

相关文章:

javascript - 如何在创建 React 应用程序时使用 webpack devServer 代理

javascript - CefGlue 使用 CefDomVisitor 检测 evenfint 监听器

javascript - 无法绘制不同形状的 div

javascript - 错误 var 未定义 - 但在使用之前已定义 -

javascript - 联系表格 7 无法在 Bootstrap Modal 内工作

javascript - 填充重叠的圆形区域

javascript - 对javascript生成器函数感到困惑

javascript - 当我使用 Django 在后端处理某些内容时,如何制作加载页面?

javascript - Knockout JS 文本输入绑定(bind)

javascript - 用JS动态添加输入然后用PHP查找?