1

在javascript中,如何拆分字符串以获取最后一个括号的内容

var str = "Lorem ipsum (I don't want this data) lorem ipsum (I want this data)";

变成了数组

["Lorem ipsum (I don't want this data) lorem ipsum "],["I want this data"]
4

2 回答 2

2

您可以使用正则表达式并匹配

var arr = str.match(/^(.*)\(([^\)]+)\)$/).slice(1);

这正好产生

["Lorem ipsum (I don't want this data) lorem ipsum ", "I want this data"]

正则表达式的在线解释

于 2013-09-10T12:12:30.623 回答
1

我总是更喜欢没有正则表达式的方法,主要是为了性能。它可能不漂亮,但它仍然有效!

var str = "Lorem ipsum (I don't want this data) lorem ipsum (I want this data)";

var s = str.lastIndexOf('(');
var e = str.lastIndexOf(')');
var l = e - s;

var data = [
    str.substr(0, s).trim(),
    str.substr(s + 1, l - 1).trim()
];

// data = ["Lorem ipsum (I don't want this data) lorem ipsum", "I want this data"] 
于 2013-09-10T12:18:15.960 回答