Javascript - Find Comma Exists In String

Viewed 87774

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!

6 Answers

Use new functions natively coming from ES6:

const text = "Hello, my friend!";
const areThereAnyCommas = text.includes(',');

Easy way to get value.

 
 let yourString = 'hellow,okey'; 
let stringResult = yourString.split(',');

Maybe a nice extra info: If my string was for example: 33 instead of 34,56,43,86,54,37 the was an error in the console like:

Uncaught TypeError: .indexOf is not a function

because the number 33 was seen as an number instead of a string. So I needed to convert the number to a string

caller = caller.toString();

   var a = [caller]; 
    if (caller.indexOf(',') > -1) { 
        var a = caller.split(',');
    }
Related