使用简单的解析器:
var words = [];
var string = "Apple Book \"Grand Piano\" Piano";
var remove_word = "Piano";
// -- tokenize input --
var i, char, looking_for_quote = false, word = "";
for (i = 0; i < string.length; i += 1) {
char = string[i];
if (char === " " && looking_for_quote === false) {
words.push(word);
word = "";
} else if (char === "\"" && looking_for_quote === false) {
looking_for_quote = true;
} else if (char === "\"" && looking_for_quote === true) {
looking_for_quote = false;
} else {
word += char;
}
}
words.push(word); // dont forget the last word
console.log(words); // gives ["Apple", "Book", "Grand Piano", "Piano"]
// -- remove words --
while (words.indexOf(remove_word) !== -1) {
words.splice(words.indexOf(remove_word), 1);
}
// reassemble output string
var out = []
for (i = 0; i < words.length; i += 1) {
word = words[i];
if (word.indexOf(" ") !== -1) {
out.push("\"" + word + "\"");
} else {
out.push(word);
}
}
console.log(out.join(" ")); // 'Apple Book "Grand Piano"'