以有效的方式从字符串中删除特定单词

Remove specific words from a string in an efficient way

我正在尝试从字符串数组中删除几个匹配的单词。下面是包含字符串

的数组
let string = ["select from table order by asc limit 10 no binding"]

我试图摆脱任何具有 order by 和 limit 及其价值的东西,并保留剩余的东西。我尝试了以下但 none 其中 elegant/efficient.

let splitString = string.split(' ');
let str1 = 'limit';
let str2 = 'order';
let str3 = 'by';
let str4 = 'asc';
let str5 = '10';

splitString = splitString.filter(x => x !== str1);
splitString = splitString.filter(x => x !== str2);
splitString = splitString.filter(x => x !== str3);
splitString = splitString.filter(x => x !== str4);
splitString = splitString.filter(x => x !== str5);

是否有从字符串中删除这些单词的正确方法? TIA

创建要删除的字符串的数组或集合,然后根据要迭代的单词是否在集合中进行过滤。

const input = ["select from table order by asc limit 10 no binding"]
const wordsToExclude = new Set(['limit', 'order', 'by', 'asc', '10']);
const words = input[0].split(' ').filter(word => !wordsToExclude.has(word));
console.log(words);

如果您实际上不想删除所有这些单词,而只想删除这样一个 sequence,请使用正则表达式匹配 limit 直到遇到数字。

const input = ["select from table order by asc limit 10 no binding"];
const result = input[0].replace(/order\b.*?\d+ /, '');
console.log(result);

如果序列之间可以插入其他数字,则在末尾匹配 limit \d+,而不仅仅是 \d+

const input = ["select from table order by 1 asc limit 33 no binding"];
const result = input[0].replace(/order\b.*?limit \d+ /, '');
console.log(result);

使用 filterincludes

const [string] = ["select from table order by asc limit 10 no binding"];
const exclude = ["limit", "order", "by", "asc", "10"];

const res = string.split(" ").filter(wd => !exclude.includes(wd));

console.log(res)

或者使用 replaceAll

const [string] = ["select from table order by asc limit 10 no binding"];
const exclude = ['limit', 'order', 'by', 'asc', '10'];

const res = exclude.reduce((str, word) => 
  str.replaceAll(word, ''), string).replaceAll(/\s+/g, ' ');
  
console.log(res)