Javascript获取括号[]之间的字符串

javascript get strings between bracket [ ]

本文关键字:之间 字符串 获取 Javascript      更新时间:2023-09-26

在我的段落中,我必须得到括号[]之间的字符串

ie)

<p id="mytext">
    this is my paragraph but I have [code1] and there is another bracket [code2].
</p>

在我的JavaScript我已经通过所有字符串,并得到数组的结果只有作为"code1"answers"code2"

提前感谢!

您可以使用正则表达式来检索这些子字符串。

问题是JS没有回溯。然后,您可以检索带有括号的文本,然后手动删除它们:

(document.getElementById('mytext').textContent
  .match(/'[.+?']/g)     // Use regex to get matches
  || []                  // Use empty array if there are no matches
).map(function(str) {    // Iterate matches
  return str.slice(1,-1) // Remove the brackets
});

或者,您可以使用捕获组,但是您必须迭代地调用exec(而不是单个match):

var str = document.getElementById('mytext').textContent,
    rg = /'[(.+?)']/g,
    match;
while(match = rg.exec(str)) // Iterate matches
  match[1];                 // Do something with it