Given these two strings:
var first = 'dog,cat,lion';
var second = 'cat';
How would I do it to know if the second var is any of the words (the ones that are separated by commas) in the first vars?
We have a global variable myString which holds a string as its value. In the event handler function, we are using the includes() method and ternary operator ( ? ) to verify whether myString contains a comma or not. Depending upon the result of the check, we will assign “Yes” or “No” to the result variable.
A comma-separated valuation (CSV) file is a demarcated file format that uses a comma to isolate the values. The data record is comprised of one or more than one field, separated by the commas. The name root for this file format is the comma-separated file format, is the use of the comma as a field extractor.
You can use Array.indexOf
:
if( first.split(',').indexOf(second) > -1 ) {
// found
}
Need IE8- support? Use a shim: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/indexOf
This would work:
if( first.match(new RegExp("(?:^|,)"+second+"(?:,|$)"))) {
// it's there
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With