+ 2

JS easiest (short code) way to check if a string contains certain text (multiple texts)...

check if the following string contains these texts: validColors: “blue”, “green”, “yellow”, “white” string “my shirt is blue”; Now, how can we check if the string contains any of the valid colors easy. Ok know there are different method, I’ll go ahead and tell u the ones I know: I could use an if statement, I could use a switch (){case...} So, I’m wondering if there is an easier way to do it besides the methods I listed above.

8th Aug 2020, 3:32 AM
Ginfio
Ginfio - avatar
2 odpowiedzi
+ 4
Regex it bro. Var mypattern = /blue|green|yellow|white/ ; Var mystring= " type here your random string with or without color" ; Var result = mypattern.test(mystring) ; Console.log(result); If console value true Means contains valid color If false it doesn't have valid color . Hope it will work as you want. Try it.
8th Aug 2020, 4:49 AM
Divya Mohan
Divya Mohan - avatar
0
Another way, array methods: const validColors = ["blue", "green", "yellow", "white"]; const str = "my shirt is blue"; const found = str.split(" ").some(r=> validColors.includes(r)); https://code.sololearn.com/cFOvBL8m5Gvb/?ref=app
8th Aug 2020, 7:03 AM
Calviղ
Calviղ - avatar