我必须在JavaScript中将此字符串拆分:
hl=windows xp \"windows xp\"
三个字。
我用过:
keywords = keywords.split(/ /);
但后来我有4个字:
windows
xp
\"windows
xp\"
我怎么能把这个字符串拆分成3个字?
编辑:我如何删除\“。
答案 0 :(得分:2)
function split(s, on) {
var words = [];
var word = "";
var instring = false;
for (var i = 0; i < s.length; i++) {
var c = s.charAt(i);
if (c == on && !instring) {
words.push(word);
word = "";
} else {
if (c != '"')
word += c;
}
if (c == '"') instring = !instring;
}
if (word != '') words.push(word); //dangling word problem solved
return words;
}
以及适合OP示例的用法示例
var hl = "windows xp \"windows xp\"";
split(hl, " "); // returns ["windows","xp","windows xp"]
答案 1 :(得分:2)
hl="windows xp \"windows xp\""
var results = hl.split(/ /);
for(var s in results) {
try {
while (results[s].search("\"") > -1) {
results.splice(s, 1);
}
} catch(e) {}
}
var quoted = hl.match(/"[^"]*"/g); //matches quoted strings
for(var s in quoted) {
results.push(quoted[s]);
}
//results = ["windows", "xp", ""windows xp""]
编辑,一个班轮:
var results = hl.match(/\w+|"[^"]*"/g).map(function(s) {
return s.replace(/^"+|"+$/g, "")
});
答案 2 :(得分:2)
这是一个简单的问题:
keywords = keywords.match(/"[^"]*"|\w+/g).map(function(val) {
if (val.charAt(0) == '"' && val.charAt(val.lenngth-1) == '"') {
val = val.substr(1, val.length-2);
}
return val;
});