+ 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.
2 Respuestas
+ 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.
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