簡體   English   中英

從字符串 JavaScript 中提取數字

[英]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);

使用這個正則表達式

  • / -> 開始
  • \\d+ -> 數字
  • /g -> end 和 g 用於全局匹配

 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM