Skip to content
Advertisement

how to Extract word combination from an string [closed]

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.

Advertisement

Answer

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"]
Advertisement