1

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?

m.edmondson
  • 30,382
  • 27
  • 123
  • 206
Arvind Thakur
  • 347
  • 1
  • 7
  • 14

3 Answers3

4
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;
    };
}
hunter
  • 62,308
  • 19
  • 113
  • 113
0

Try using this trick:

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

(It will create object of array using JSON)

Andrey S
  • 71
  • 3
0

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

Community
  • 1
  • 1
Nivas
  • 18,126
  • 4
  • 62
  • 76