Reputation: 4735
I have an array like this:
var people = [
'<option value=\'64\'>Tom',
'<option value=\'76\'>Dan',
];
I am looping through each item in the array to extract the value (like the number 64 in the first item) and the text (like Tom in the first item). I tried multiple ways of extracting these details from each item but I am unable to. I even tried using substrings and other methods. Can someone tell me how to extract this information?
Upvotes: 0
Views: 764
Reputation: 382102
You should use a regular expression in such a case.
For example:
var things = people.map(function(s){
return s.match(/(\d+)\W+(\w+)$/).slice(1)
});
This builds this array:
[ ["64", "Tom"], ["76", "Dan"] ]
You might want to adapt it for your precise needs:
match
, if some strings might be invalidNote that you probably shouldn't have such an array to start with. If you generate it server-side, you should opt for the generation of a JSON structure instead and let the client script build the interface from the data, instead of building it from something which is neither clean data nor GUI.
Upvotes: 4
Reputation: 12854
You can use multiple split :
var str = '<option value=\'64\'>Tom';
var tmpStr = str.split("'");
var number = (tmpStr[1].split("\\"))[0];
var name = (tmpStr[2].split(">"))[1];
document.write(number + " " + name);
Upvotes: 1