在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"]
在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"]
您可以使用正则表达式并匹配:
var arr = str.match(/^(.*)\(([^\)]+)\)$/).slice(1);
这正好产生
["Lorem ipsum (I don't want this data) lorem ipsum ", "I want this data"]
我总是更喜欢没有正则表达式的方法,主要是为了性能。它可能不漂亮,但它仍然有效!
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"]