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

Jas*_* Ko -1 javascript

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

<p id="mytext">
    this is my paragraph but I have [code1] and there is another bracket [code2].
</p>
Run Code Online (Sandbox Code Playgroud)

在我的JavaScript上,我遍历了所有字符串,并仅以“ code1”和“ code2”获取数组的结果

先感谢您!

Ori*_*iol 6

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

问题是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
});
Run Code Online (Sandbox Code Playgroud)

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

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