Salman
Salman

Reputation: 82

how to get values from an array in javascript?

let the array be var array= [ "me=Salman","Profession=student","class=highschool" ]

How do I extract the value of 'me' here?

Upvotes: 0

Views: 56

Answers (3)

KillaBee
KillaBee

Reputation: 139

Try this:

var a = [ "me=Salman" , "Profession=student" , "class=highschool" ];
var result = a.filter(function(e){return /me=/.test(e);})[0]; // Find element in array
result = result.length ? result.split('=').pop() : null; // Get value

Or function:

var array = [ "me=Salman" , "Profession=student" , "class=highschool" ];

function getVal(arr, key){
   var reg = new RegExp(key + '=');
   var result = arr.filter(function(e){ return reg.test(e)})[0];
   return result.length ? result.split('=').pop() : null;
}

console.log( getMe(array, 'me') );

Upvotes: 0

Louis Cedarholm
Louis Cedarholm

Reputation: 1

You will need to search the array for your desired portion of the string, then remove what you searched for from the indicated string.

var array = [ "me=Salman" , "Profession=student" , "class=highschool" ];
var findMatch = "me=";
var foundString = "Did not find a match for '"+findMatch+"'.";
var i = 0;

for (i = 0; i<array.length; i++) //search the array
{
    if(array[i].indexOf(findMatch) != -1) // if a match is found
    {
         foundString = array[i]; //set current index to foundString
         foundString = foundString.substring(findMatch.length, array[i].length); //remove 'me=' from found string
    }
}

Upvotes: 0

TheGr8_Nik
TheGr8_Nik

Reputation: 3200

Try this:

var result = '';
for(var values in array){
  if(values.indexOf('me=') !== -1 ){
    result = values.split('=')[1];
    break;
  }
}

Upvotes: 1

Related Questions