Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

Extract Number จาก String ด้วย JavaScript

เรียนรู้ extract ตัวเลข 1 หรือหลายตัวจาก string ด้วย JavaScript

String มีตัวเลข อยาก extract เฉพาะตัวเลข ใช้ match() method

String มี 1 ตัวเลข (1995) assign ให้ stringWithOneNumber:

const stringWithOneNumber = "JavaScript was invented in 1995 by Brendan Eich";

Attach match() argument \d+ → match(/\d+/)

stringWithOneNumber.match(/\d+/)

Note: \d+ = RegEx meta character "match 1 or more digits"

Print result:

console.log(stringWithOneNumber.match(/\d+/)); // ["1995"]

Extract Multiple Numbers

String มี 2+ numbers? ใส่ global g flag ใน match argument

const stringWithMultipleNumbers = "JavaScript was invented in 1995 by Brendan Eich, and is still used in 2020";
stringWithMultipleNumbers.match(/\d+/g);
console.log(stringWithMultipleNumbers.match(/\d+/g)); // ["1995", "2020"]