【问题标题】:How to get the match index in the string using javascript?如何使用javascript获取字符串中的匹配索引?
【发布时间】: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]”

“我是 &lt;span&gt;some user&lt;/span&gt; 更多文字‘另一个用户’”

我该怎么做?

基本实现如下,

获取括号中的字符串。 从括号中的字符串中提取 @ 字符后的值。 然后将提取的值嵌入到 span 标签中,并将它们放在原始字符串中。

有人可以帮我解决这个问题吗?谢谢。

【问题讨论】:

  • 请先自己试一试。一旦您尝试过并遇到问题,请在 SO 上发布另一个问题,说明您遇到的具体问题
  • 我已经解释了我遇到问题的地方。找到匹配项后,我不知道如何在字符串中替换它们。

标签: javascript


【解决方案1】:

如果您想将[id@name] 部分替换为格式化名称(例如&lt;span&gt;name&lt;/span&gt;),您可以使用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 参数(新子字符串)中使用捕获组

【讨论】:

  • 看起来你已经改变了正则表达式中的某些内容。你能解释一下为什么需要这些改变吗?这种方法看起来不错。
  • 哦,是的。我忘记了。我不得不转义两个括号,因为我们需要从字面上匹配它们。我无法让我的浏览器接受原始的正则表达式,而且我不熟悉 ? 并否定匹配 ^,所以我假设带有空格的文本 ([A-z\s]+) 就足够了。可以根据需要添加符号和数字。
【解决方案2】:

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

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);

【讨论】:

    【解决方案3】:

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

    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>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-10-01
      • 2019-10-10
      • 1970-01-01
      • 2014-08-21
      • 2013-11-22
      • 2018-09-23
      • 2017-01-09
      • 2015-11-14
      相关资源
      最近更新 更多