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

时间:2015-07-25 21:42:16

标签: javascript

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

之间的字符串

IE)

PFCloud.callFunctionInBackground("getManyObjectsById", withParameters: dataID) {
  (objects: [AnyObject]?, error: NSError?) -> Void in
      // objects should be an array of objects corresponding to the ids
}

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

提前谢谢你!

1 个答案:

答案 0 :(得分:4)

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

问题在于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
相关问题