Arvind Thakur
Arvind Thakur

Reputation: 347

how to get index of a string from a list?

I have a list like

_Value1 = "'apple','ball','cat'....so on";

If I know that apple exists in above list.How to get index of whole string from the list.Like apple should have the index 1, ball should have 2 and so on.

What is the javascript code for this stuff?

Upvotes: 1

Views: 5139

Answers (3)

hunter
hunter

Reputation: 63532

var _Value1 = "'apple','ball','cat'";

// split the string on ","
var values = _Value1.split(",");

// call the indexOf method
var index = values.indexOf("'apple'");

working example: http://jsfiddle.net/Yt5fp/


You can also do this check if it is an older browser and add the indexOf method if it doesn't exist

if (!Array.prototype.indexOf)
{
    Array.prototype.indexOf = function(elt /*, from*/) {
        var len = this.length;
        var from = Number(arguments[1]) || 0;
        from = (from < 0) ? Math.ceil(from) : Math.floor(from);
        if (from < 0) from += len;
        for (; from < len; from++) {
            if (from in this && this[from] === elt) return from;
        }
        return -1;
    };
}

Upvotes: 4

Nivas
Nivas

Reputation: 18354

Assuming your strings (apple, ball, cat...) will not have a , in them:

You can split a string based on a delimiter:

var split = _values.split(",")

You will get an array of strings: {'apple', 'ball', 'cat'}

You can use the indexOf method in the array to find the position of an element:

split.indexOf('apple')

indexOf is not supported by IE. You can use the alternative in How to fix Array indexOf() in JavaScript for Internet Explorer browsers

Upvotes: 0

Andrey S
Andrey S

Reputation: 71

Try using this trick:

_Array = eval("[" + _Value1 + "]");

(It will create object of array using JSON)

Upvotes: 0

Related Questions