我正在嘗試從字串陣列中洗掉幾個匹配的單詞。下面是包含字串的陣列
let string = ["select from table order by asc limit 10 no binding"]
我試圖擺脫任何具有 order by 和 limit 及其價值的東西,并保留剩余的東西。我嘗試了以下方法,但沒有一個是優雅/高效的。
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
uj5u.com熱心網友回復:
制作要洗掉的字串的陣列或 Set,然后根據被迭代的單詞是否在 Set 中進行過濾。
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);
如果您實際上不想洗掉所有這些單詞,而只想洗掉這樣的序列,請使用正則運算式進行匹配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);
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/456429.html
