Javascript 将引号添加到除()
我有这样一句话:Javascript 将引号添加到除(),javascript,Javascript,我有这样一句话: (CAR AND BUS) OR TRAM 我需要在所有单词中添加引号,除了AND(可以是或代替AND): 因此我创建了这样一个代码: word.replace(/"/g, '').split(" ").map(e => ["AND", "OR"].includes(e) ? e : '"' + e + '"').join(" "); 但作为输出,我有一个格式不正确的查询,如 “(汽车”和“公共汽车”或“电车” 我不需要在()中包含引号,以便作为我期望的输出 ("CA
(CAR AND BUS) OR TRAM
我需要在所有单词中添加引号,除了AND(可以是或代替AND):
因此我创建了这样一个代码:
word.replace(/"/g, '').split(" ").map(e => ["AND", "OR"].includes(e) ? e : '"' + e + '"').join(" ");
但作为输出,我有一个格式不正确的查询,如
“(汽车”和“公共汽车”或“电车”
我不需要在()中包含引号,以便作为我期望的输出
("CAR" AND "BUS") OR "TRAM"
我怎样才能达到这样的结果呢?“(汽车和公共汽车)或电车”。替换(/([a-zA-Z]+)/gi,函数(单词){
"(CAR AND BUS) OR TRAM".replace(/([a-zA-Z]+)/gi, function(word){
if(["AND", "OR"].indexOf(word) < 0) return `"${word}"`;
else return word
})
if([“AND”,“OR”].indexOf(word)<0)返回“${word}”;
否则返回单词
})
“(汽车和公共汽车)或有轨电车”。替换(/([a-zA-Z]+)/gi,功能(单词){
if([“AND”,“OR”].indexOf(word)<0)返回“${word}”;
否则返回单词
})
使用replace()
演示:
console.log(((汽车和公共汽车)或电车)。使用replace()替换(/(?!和|或)(\b[^\s]+\b)/g,“$1”)
演示:
console.log((汽车和公共汽车)或TRAM.replace(/(?!AND | OR)(\b[^\s]+\b)/g,“$1”)
有很多方法可以解决您的任务。这里有一个更程序化的,它不使用正则表达式
基本上,您的任务是将句子拆分为单词,然后处理每个单词,检查是否需要处理,然后应用给定的规则集
当然,这可以通过使用正则表达式(参见其他答案)编写得更简洁,但特别是当您的团队中有一些人不是那么多才多艺时,有时更具表达力的方法也很好
var sentence = "(CAR AND BUS) OR TRAM"; // Input data
var words = sentence.split(" "); // Get each word of the input
var exclude = ["AND", "OR"]; // Words that should be ignored when processing
var result = []; // result goes here
words.forEach(word=>{ // loop over each word
if(exclude.includes(word)){ // exclude from further processing?
result.push(word); //yes: put into result
} else{ //no: remove ( and ) and enclose with quoationsmark then put into result
result.push("\""+word.replace("(","").replace(")","")+"\"");
}
}
);
console.log(result.join(" "));
有很多方法可以解决您的任务。这里有一个更程序化的,它不使用正则表达式
基本上,您的任务是将句子拆分为单词,然后处理每个单词,检查是否需要处理,然后应用给定的规则集
当然,这可以通过使用正则表达式(参见其他答案)编写得更简洁,但特别是当您的团队中有一些人不是那么多才多艺时,有时更具表达力的方法也很好
var sentence = "(CAR AND BUS) OR TRAM"; // Input data
var words = sentence.split(" "); // Get each word of the input
var exclude = ["AND", "OR"]; // Words that should be ignored when processing
var result = []; // result goes here
words.forEach(word=>{ // loop over each word
if(exclude.includes(word)){ // exclude from further processing?
result.push(word); //yes: put into result
} else{ //no: remove ( and ) and enclose with quoationsmark then put into result
result.push("\""+word.replace("(","").replace(")","")+"\"");
}
}
);
console.log(result.join(" "));