Search code examples
javascriptarraysstringecmascript-6ecmascript-5

Remove specific words from a string in an efficient way


I am trying to strip out a couple of matching words from an array of string. Below is the array containing the string

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

I am trying to get rid of any that has order by and limit and its value and preserving the remaining. I have tried the following but none of them are 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);

Is there a proper way of getting rid of those words from the string? TIA


Solution

  • Make an array or Set of the strings you want to remove, then filter by whether the word being iterated over is in the 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);

    If you don't actually want to remove all of those words, but only such a sequence, use a regular expression to match limit until you come across numbers.

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

    If additional numbers can come in between the sequence, match limit \d+ at the end, rather than just \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);