Javascript - Find Comma Exists In String
.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.
Use new functions natively coming from ES6:
const text = "Hello, my friend!";
const areThereAnyCommas = text.includes(',');
Try using indexOf
function:
if (string.indexOf(',') > -1) { string.split(',') }