在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"]
答案 0 :(得分:2)
您可以使用正则表达式和match:
var arr = str.match(/^(.*)\(([^\)]+)\)$/).slice(1);
这恰好产生了
["Lorem ipsum (I don't want this data) lorem ipsum ", "I want this data"]
答案 1 :(得分: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"]