我想创建一个从右到左的括号内文本数组。所以如果我们有这个文本:
const text = "I was sent [to earth] for the [next time]"
那么期望的结果将是:
["next time", "to earth"]
到目前为止,我只找到了一个正则表达式来选择括号的内部:
这是原型(不是我正在寻找的代码):
const text = "I was sent [to earth] for the [next time]"
const result = text.replace(
/(?<=[)(.*?)(?=])/g, // this is the regex to select inside of the brackets
'inside bracket'
);
console.log(result);
您可以使用match (with look arounds) + reverse
:
const text = "I was sent [to earth] for the [next time]"
var arr = text.match(/(?<=[)[^]]+(?=])/g).reverse()
console.log(arr)
//=> ["next time", "to earth"]