Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Isolating values from a string

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;

like image 732
Eyal C Avatar asked Apr 17 '26 14:04

Eyal C


2 Answers

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
like image 119
Hanlet Escaño Avatar answered Apr 20 '26 02:04

Hanlet Escaño


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
like image 27
Blazemonger Avatar answered Apr 20 '26 02:04

Blazemonger



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!