[英]Extract number from string JavaScript
有誰知道在 JavaScript 中從字符串中提取數字的方法?
例子:
1 banana + 1 pineapple + 3 oranges
我的意圖是將結果放入數組或 JSON 或其他內容中。
結果:
[1,1,3]
var result= "1 banana + 1 pineapple + 3 oranges";
result.match(/[0-9]+/g)
使用String.prototype.match()
和parseInt()
:
const s = "1 banana + 1 pineapple + 3 oranges"; const result = (s.match(/\\d+/g) || []).map(n => parseInt(n)); console.log(result);
使用這個正則表達式
var str="1 banana + 1 pineapple + 3 oranges",mats=[]; str.match(/\\d+/g).forEach(function(i,j){mats[j]=parseInt(i);}); console.log(mats);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.