这将做到:
function splitWithBracket(str) {
var out = str.split(" "), i = 0, begin, end;
function findNext(chr) {
while (i < out.length) {
if (out[i].indexOf(chr) != -1) {
out[i] = out[i].replace(chr, "");
return(i);
}
i++;
}
return(-1);
}
do {
end = -1;
begin = findNext("[");
if (begin != -1) {
end = findNext("]");
if (end != -1) {
var tmp = out.splice(begin, end - begin + 1);
out.splice(begin, 0, tmp.join(" "));
i = begin + 1;
}
}
} while (end != -1);
return(out);
}
工作演示:http: //jsfiddle.net/jfriend00/jLNXa/
或使用正则表达式替换/匹配的版本:
function splitWithBracket(str) {
str = str.replace(/\[([^\]]*)\]/g, function(m, p1) {
return(p1.replace(/ /g, "!!xx!!"));
});
var out = str.split(" ");
for (var i = 0; i < out.length; i++) {
out[i] = out[i].replace(/!!xx!!/g, " ")
}
return(out);
}
工作演示:http: //jsfiddle.net/jfriend00/Hbjzk/