在string-Javascript中替换单词和短语
假设我有一串这样的单词和短语在string-Javascript中替换单词和短语,javascript,regex,Javascript,Regex,假设我有一串这样的单词和短语 var a = "Apple Book \"Grand Piano\" Piano"; 我有一些类似的变量 var b = "Piano"; var c = "Grand Piano"; a = a.replace(b,"") 如何从字符串a中删除变量b或c。目前,我一直在使用javascripts替换这样的方法 var b = "Piano"; var c = "Grand Piano"; a = a.replace(b,"") 这样做的问题是,它会从短
var a = "Apple Book \"Grand Piano\" Piano";
我有一些类似的变量
var b = "Piano";
var c = "Grand Piano";
a = a.replace(b,"")
如何从字符串a中删除变量b或c。目前,我一直在使用javascripts替换这样的方法
var b = "Piano";
var c = "Grand Piano";
a = a.replace(b,"")
这样做的问题是,它会从短语“Grand Piano”中删除Piano一词,而我只想在引号之外删除Piano一词。我一直在尝试使用RegExp获得某种解决方案,但一直无法解决。我想我可以把字符串拆分成一个数组,然后在for循环中比较变量a/b,然后删除匹配的位置,然后把字符串放回一起,但不确定这是否是最好的方法。如果有人能给我指引正确的方向,我会非常感激的
多谢各位
var a = "Apple Book \"Grand Piano\" Piano Pear";
var b = "Piano";
var c = "Grand Piano";
var regexp = new RegExp('('+b+')|('+c+')', 'g');
a = a.replace(regexp, '');
您需要同时执行所有替换,并使用与需要排除的所有内容匹配的regexp。
如果需要,请确保在将字符串添加到RegExp之前对其进行转义。前几天也有类似的情况,您可以根据自己的情况进行调整:
Piano(?!(?:[^"]*"[^"]*")*[^"]*"[^"]*$)
正则表达式基本上确保要替换的字符串前面没有奇数个引号
当然,您可以使用简单的解析器将正则表达式更改为接受变量,而不仅仅是Piano
:
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"'
var-words=[];
var string=“苹果书”大钢琴“钢琴”;
var remove_word=“Piano”;
//--标记化输入--
变量i,char,正在查找quote=false,word=“”;
对于(i=0;i
我需要一些关于更换规则的说明。您是否将Grant Piano
视为一个词(因为引号)?因此,Apple
和Book
是两个独立的词。这是正确的吗?如果是这样,您的语言是不规则的,您不能使用正则表达式。您可以先按大小删除这些术语。。。也许吧。是的,大钢琴被视为一个词,苹果和书也被视为一个词。你试过a.replace(a | | b,“”)吗?太棒了。解决了我的问题。非常感谢大家。谢谢Jerry。这也非常有效,但对于简单的单线解决方案,我同意Jerry的答案。谢谢你这么做。