【问题标题】:javascript get strings between bracket [ ] [duplicate]javascript获取括号[]之间的字符串[重复]
【发布时间】:2015-10-16 08:38:21
【问题描述】:

在我的段落中,我必须得到括号 []

之间的字符串

即)

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

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

提前致谢!

【问题讨论】:

  • 那么你尝试了什么?

标签: javascript


【解决方案1】:

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

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

(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

【讨论】:

  • @GeorgeJempty 是的,但是由于 JS 没有lookbehinds,我应该使用捕获组,它不会被全局match 检索到,所以我应该在循环中使用exec ,而且我认为不会简单得多。
  • 好吧,我也加入了这个替代方案。
  • @GeorgeJempty 好吧,循环可以push 将每个子字符串指向一个数组。这留给读者作为练习。
猜你喜欢
  • 2012-07-15
  • 1970-01-01
  • 2016-03-24
  • 1970-01-01
  • 2016-08-30
  • 1970-01-01
  • 2023-03-16
  • 2018-07-30
  • 1970-01-01
相关资源
最近更新 更多