1

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.

0

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

2 Comments

Woah amazing /dog|cat/g its regex right ? what are some articles that can help me in these situations? thank you in advance.
@alireza I added a link to MDN in the answer, and another one with tons of info is regular-expressions.info Also a good one to test regular expressions is regex101.com
2

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:

find and return string with a specific word in it in js

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.