Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript - Find Comma Exists In String

Tags:

javascript

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!

like image 223
logic-unit Avatar asked Jul 29 '11 10:07

logic-unit


4 Answers

Try using indexOf function:

if (string.indexOf(',') > -1) { string.split(',') } 
like image 143
ChristopheCVB Avatar answered Sep 19 '22 18:09

ChristopheCVB


Use new functions natively coming from ES6:

const text = "Hello, my friend!"; const areThereAnyCommas = text.includes(','); 
like image 38
danigonlinea Avatar answered Sep 18 '22 18:09

danigonlinea


.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.

like image 33
Aron Rotteveel Avatar answered Sep 20 '22 18:09

Aron Rotteveel


var strs;
if( str.indexOf(',') != -1 ){
    strs = str.split(',');
}
like image 40
Talha Ahmed Khan Avatar answered Sep 18 '22 18:09

Talha Ahmed Khan