Eyal
Eyal

Reputation: 1709

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;

Upvotes: 3

Views: 335

Answers (8)

Blazemonger
Blazemonger

Reputation: 92893

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

Upvotes: 2

dc5
dc5

Reputation: 12441

If you string is indeed well known/formed:

var str = "255, 100, 0";
var vals = str.split(', '); // <<= you can split on multiple chars

var x = +vals[0]; // <<= coerces to a number

// lather, rinse, repeat

Upvotes: 0

Sobin Augustine
Sobin Augustine

Reputation: 3765

try using the JavaScript split() Method

var str = "255, 100, 0";
var elements = str.split(','); //take values to an array
//access the elements with array index
var x = elements[0];
var y = elements[1];
var z = elements[2];

w3schools documentation here

Upvotes: 0

Hanlet Esca&#241;o
Hanlet Esca&#241;o

Reputation: 17370

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

Upvotes: 2

Jonathan Petitcolas
Jonathan Petitcolas

Reputation: 4574

Assuming you got the following string:

var string = "x = 255; y = 100; z = 0;";

You should indeed play with split function:

var values = [];
var expressions = string.split("; ");
for (var i = 0, c = expressions.length ; i < c ; i++) {
    values.push(expressions[i].split("= ").pop() * 1);
}

In expressions, you will get values like x = 255. Then, you just have to cut to the =. I just multiply it by 1 to cast it into a int.

Upvotes: 0

r8n5n
r8n5n

Reputation: 2059

Have look at the Javascript split method https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split

var str = "255, 100, 0";
var array = str.split(',');

Then you can loop through the array and create your variables, or better use the array directly

Upvotes: 0

DevlshOne
DevlshOne

Reputation: 8457

var string = "255, 100, 0";
var arrNums = string.split(",");

Will put each of the numbers into an element of the arrNums array.

Upvotes: 0

var str = "255, 100, 0";
var str_new = str.split(",");

var x = str_new[0];
var y = str_new[1];
var z = str_new[2];

Upvotes: 1

Related Questions