I need to find if a comma exists in a javascript string so I know whether to do str.split(',') on it or not.
Is this the correct way: var myVar = str.search(','); ?
If the value of myVar is greater than 0 (zero) then there is a comma in the string?
I'm just not sure if I've got the parameter right in search()
Thanks!
Try using indexOf function:
if (string.indexOf(',') > -1) { string.split(',') } 
                        Use new functions natively coming from ES6:
const text = "Hello, my friend!"; const areThereAnyCommas = text.includes(','); 
                        .search() is used for regular expressions, making it a bit overkill for this situation.
Instead, you can simply use indexOf():
if (str.indexOf(',') != -1) {
    var segments = str.split(',');
}
.indexOf() returns the position of the first occurrence of the specified string, or -1 if the string is not found.
var strs;
if( str.indexOf(',') != -1 ){
    strs = str.split(',');
}
                        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