want to find a way to search for words in a string and return them In the same order
so here is an example I am searching for dog and cat :
let story = "The dog ran away, The cat is unhappy,cat watched the sky and saw adog"
result should be :
return dog cat cat dog notice the last one on the story string is "adog" not a "dog" we just want to return the value whenever the dog combination appears.
a simple summary of the text above:
how to return a specific combination of characters in a string when they are surrounded by other characters.
You can use regular expressions, using the | to separate the strings to search for.
The
match()method retrieves the result of matching a string against a regular expression.
let story = "The dog ran away, The cat is unhappy,cat watched the sky and saw adog"
const search = /dog|cat/g;
console.log(story.match(search));
// will result in ["dog", "cat", "cat", "dog"]
In string format:
let str = 'a dog see a cat, also cat and adog ..';
let filtered = str.split(' ').filter(x => x.match(/(dog|cat)/g)).join(' ');
console.log(filtered.match(/(dog|cat)/g).join(','));
In array format:
let str = 'a dog see a cat, also cat and adog ..';
let filtered = str.split(' ').filter(x => x.match(/(dog|cat)/g)).join(' ');
console.log(filtered.match(/(dog|cat)/g));
Here, see the first comment: