0

I'd like to extract the numbers from the string. (E.g. I want the 24 and 380 from the string 24:380) I'd like to assign it in respective variables. Is there any way I could do that?

I couldn't find any solution to this problem.

Kyle
  • 17
  • 4

2 Answers2

0

You can use RegEx:

const paragraph = 'The quick brown 45 jumps over the lazy 23:12. It barked.';
const regex = /(\d+)/g;
const found = paragraph.match(regex);

console.log(found);
// expected output: Array ["45", "23", "12"]
Mox
  • 564
  • 2
  • 8
  • 20
0

Use match or split with regex:

const str = '24:380';


// This returns exactly and only 24 and 380.
const regex = /24|380/g
const resultArr = str.match(regex);
for (const output of resultArr) console.log(output);
// output:
// 24
// 380


// This returns any string seperated by ':'.
const regex2 = /:/g
const resultArr2 = str.split(regex2)
for (const output of resultArr2) console.log(output);
// output:
// 24
// 380


// This returns any numbers seperated by any string that is not number.
const regex3 = /[0-9]+/g
const resultArr3 = str.match(regex3)
for (const output of resultArr3) console.log(output);
// output:
// 24
// 380
Ping
  • 891
  • 1
  • 2
  • 10