In JavaScript, let's assume we have a string: "The quick brown fox jumps over the lazy dog"
And then we have a list of substrings, say: ["dog", "brown", "The", "jumps"]
How to filter every other character from the string, but not the substrings given as the list?
So the result in this case should be: "Thebrownjumpsdog"
The first solution that came to my mind was to use a loop, and RegExp on every iteration i.e:
const listOfSubstrings = ["dog", "brown", "The", "jumps"];
let theString = "The quick brown fox jumps over the lazy dog";
for (const substring of listOfSubstrings) {
theString = theString.replace(new RegExp(`[^${substring}]`, "g"), "");
}
However, the if we take a closer look (or test) the code, we see and understand that there is nothing left after the loop: On every iteration everything but the current element in the list is removed. To be precise, nothing is left after the second iteration.
So, any ideas how the end result, I provided, could be achieved given the string and the list of substrings?
CodePudding user response:
You could match these substrings and join them:
let res = s.match(/(?:dog|brown|The|jumps)/g).join("");
See this JS demo at tio.run or regex demo at regex101
To build the pattern from the listOfSubstrings
let regex = new RegExp('(?:' listOfSubstrings.join("|") ')','g');
CodePudding user response:
You can try this:
const listOfSubstrings = ["dog", "brown", "The", "jumps"];
let theString = "The quick brown fox jumps over the lazy dog";
let result = "";
const theStringArray = theString.split(" ");
theStringArray.forEach(s => {
if(listOfSubstrings.includes(s)){
result = s;
}
})
But this might be slower if your listOfSubstrings is larger. For that, you can convert your listOfSubstrings to dictionary
const listOfSubstrings = ["dog", "brown", "The", "jumps"];
let theString = "The quick brown fox jumps over the lazy dog";
let result = "";
const theStringArray = theString.split(" ");
let substrings = {};
// converting array to dictionary
listOfSubstrings.forEach(e=>{
substrings[e] = e;
})
theStringArray.forEach(s => {
if(substrings[s] !== undefined){
result = s;
}
})
The reason why using dictionary is that checking if the key exist, works in O(1) but array.includes works in O(n).