Javascript – Find Comma Exists In String

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(',');
}

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(',');
    }


The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .
Read More:   react native how to call multiple functions when onPress is clicked

Similar Posts