Lets say I have a string "255, 100, 0". How do I isolate each value before the comma and inserting it into a var?
I mean:
x = 255;
y = 100;
z = 0;
var str = "255, 100, 0";
var d = str.split(",");
var x = parseInt(d[0],10); // always use a radix
var y = parseInt(d[1],10);
var z = parseInt(d[2],10);
console.log(x); //255
console.log(y); //100
console.log(z); //0
Using the under-appreciated String.match() method will return an array of all matches, in the order they are found:
var str = "255, 100, 0",
regex = /(\d+)/g, // g is for "global" -- returns multiple matches
arr = str.match(regex);
console.log(arr); // ["255","100","0"] -- an array of strings, not numbers
To convert them into numbers, use a simple loop:
for (var i=0,j=arr.length; i<j; i++) {
arr[i] *= 1;
}; // arr = [255, 100, 0] -- an array of numbers, not strings
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With