user8719966
user8719966

Reputation:

how to extract numbers from a long string

I have this string, I'm using JavaScript in my project and I have this

338 km 3 heurs 28 minutes

What I want is extract only the numbers, I want to create a method which could put every number in a variable.

I tried that but it doesnt work :

var num = "338 km 3 heurs 28 minutes".match(/[\d]+/g)
var num = "338 km 3 heurs 28 minutes".match(/[\d]+/g)
var num = "338 km 3 heurs 28 minutes".match(/[\d]+/g)

Upvotes: 0

Views: 59

Answers (2)

Ori Drori
Ori Drori

Reputation: 191976

You can use array destructuring to assign each number to a variable or a constant.

Note: I'm using the Array#map with the Number function to convert each number string to an actual number, but you can skip this if you just want the number strings.

const [a, b, c] = "338,7 km 3 heurs 28 minutes"
  .match(/\d+(:?,\d+)?/g) // match numbers with commas as decimal separator
  .map((n) => Number(n.replace(',', '.'))); // convert the comma to dot, and convert to number

console.log(a);
console.log(b);
console.log(c);

Upvotes: 3

Scott Marcus
Scott Marcus

Reputation: 65808

You were close. Your code returns an array of matches. You can assign each array item to its own variable, but why? They are all in the array:

var num = "338 km 3 heurs 28 minutes".match(/[\d]+/g);
console.log(num.join()); // Join the array values into a string

// Or, enumerate the array:
num.forEach(function(n){
  console.log(n);
});

// Or, extract the values individually:
console.log(num[0], num[1], num[2]);

// Or, you could assign a variable to each index:
var a = num[0];
var b = num[1];
var c = num[2];

console.log(a,b,c);

// Or, use the more modern destructuring syntax to do the same thing:
const [x,y,z] = "338 km 3 heurs 28 minutes".match(/[\d]+/g);
console.log(x,y,z);

Upvotes: 0

Related Questions