Search code examples
javascriptstring-parsing

Separate by comma (,) and check if any of the values is = "something"


How can I somehow split/separate my JavaScript variable by comma (,).
And then check if value-of-any-of-the-separated-strings = "something"

For example, my variable has the value 1,2,3,4,5,6,7,8,9,10,2212312, and I want to check if any of the numbers are = 7 in a IF-Statement.

Does anyone have any ideas how this can be done?


Solution

  • First, split the string by ",". Then, use indexOf on the split-string array to see if the target string is found (-1 means it wasn't found in the array). For example:

    var str = "1,2,3,4,5,6,7,8,9,10,10,2212312";
    var split_str = str.split(",");
    if (split_str.indexOf("7") !== -1) {
        // Original string contains 7
    }
    

    References: