2

I am trying to grab some values out of a sting that looks like this:

W1:0.687268668116, URML:0.126432054521, MH:0.125022031608, W2:0.017801539275, S3:0.00869514129605, PC1:0.00616885024382, S5L:0.0058163445156, RM1L:0.00540508783268, C2L:0.00534633687797, S4L:0.00475882733094, S2L:0.00346630632748

I want to make an array of all the keys and another array of all the values i.e. [W1, URML, MH…] and [0.687268668116, 0.126432054521...] I have this snippet that does the trick, but only for the first value:

var foo = str.substring(str.indexOf(":") + 1);
1
  • 2
    str.split(" ").map(function(elem) { return elem.split(":")[1] }; Commented Nov 27, 2013 at 15:00

4 Answers 4

7

Use split().
Demo here: http://jsfiddle.net/y9JNU/

var keys = [];
var values = [];

str.split(', ').forEach(function(pair) {
  pair = pair.split(':');
  keys.push(pair[0]);
  values.push(pair[1]);
});

Without forEach() (IE < 9):

var keys = [];
var values = [];
var pairs = str.split(', ');

for (var i = 0, n = pairs.length; i < n; i++) {
  var pair = pairs[i].split(':');
  keys.push(pair[0]);
  values.push(pair[1]);
};
Sign up to request clarification or add additional context in comments.

1 Comment

This is a nice implementation but be aware that forEach is only implemented in browsers supporting ECMAScript5 so you will need a shim for IE8 and earlier, which is still a large proportion of internet users.
4

This will give you the keys and values arrays

var keys   = str.match(/\w+(?=:)/g),
    values = str.match(/[\d.]+(?=,|$)/g);

RegExp visuals

/\w+(?=:)/g

/\w+(?=:)/g

/[\d.]+(?=,|$)/g

/[\d.]+(?=,|$)/g


And another solution without using regexp

var pairs  = str.split(" "),
    keys   = pairs.map(function(e) { return e.split(":")[0]; }),
    values = pairs.map(function(e) { return e.split(":")[1]; });

Comments

1

JSFiddle

var str = "W1:0.687268668116, URML:0.126432054521, MH:0.125022031608, W2:0.017801539275, S3:0.00869514129605, PC1:0.00616885024382, S5L:0.0058163445156, RM1L:0.00540508783268, C2L:0.00534633687797, S4L:0.00475882733094, S2L:0.00346630632748";

var all = str.split(","),
    arrayOne = [],
    arrayTwo = [];

for (var i = 0; i < all.length; i++) {
    arrayOne.push(all[i].split(':')[0]);  
    arrayTwo.push(all[i].split(':')[1]);
}

Comments

0

parse the string to an array

var str = "W1:0.687268668116, URML:0.126432054521, MH:0.125022031608, W2:0.017801539275";

var tokens = str.split(",");

var values = tokens.map(function (d) {
    var i = d.indexOf(":");
    return +d.substr(i + 1);
});

var keys = tokens.map(function (d) {
    var i = d.indexOf(":");
    return d.substr(0, i);
});

console.log(values);
console.log(keys);

http://jsfiddle.net/mjTWX/1/ here is the demo

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.