繁体   English   中英

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

[英]How to get the match index in the string using javascript?

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

考虑字符串original_string =“我是[1 @ some用户]还有一些文本[2 @ another用户]”

我正在使用模式/ [\\ 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参数(新子字符串)中使用捕获组

您将需要改进正则表达式,这对于给定的示例来说效果很好,

let originalString = "i am [1@some user] some more text [2@another user]";

const matches = originalString.match(/[^[\]]+(?=])/g);
let newString = originalString;
matches.forEach(match => {
  newString = newString.replace(
    `[${match}]`,
    `<span>${match.split("@")[1]}</span>`
  );
});
console.log(newString);

真的不知道这是否对您有帮助,但是一个快速的解决方案可能是:

HTML:

<div>
  <p>user 1 : <span id="first"></span></p>
  <p>user 2: <span id="second"></span></p>
</div>

<script>
let string = "first user is [1@user1] and second is [2@user2]";

let users = string.match(/[^[\]]+(?=])/g).map(el => el.split('@')[1]);

document.getElementById('first').innerText = users[0];
document.getElementById('second').innerText = users[1];
</script>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM