使用 JavaScript 從字串中提取數字


JavaScript 中,有多種方法可以從字串中提取數字。一種方法是使用 match() 方法 和正則表示式來搜尋字串中所有數字。另一種方法是使用 replace() 方法 和正則表示式來刪除字串中所有非數字字元,只留下數字。

讓我們透過一些例子來了解每種方法。

使用 match() 方法和正則表示式

正則表示式是一種搜尋模式,我們可以透過組合多個字母和特殊字元來建立。我們可以使用 '/\d+/' 模式來搜尋字串中的數字。在 '\d+' 模式中,d 表示 0 到 9 之間的數字,'+' 表示查詢至少一個數字。

因此,我們可以將該正則表示式作為 JavaScript 內建 match 方法的引數,以搜尋給定字串中的所有數字。

語法

使用者可以按照以下語法從給定的字串中提取所有數字。

let str = "Sampll323435 Stringrfd23232ftesd3454!";
let numbers = str.match('/\d+/');

在上面的語法中,我們使用了match() 方法,該方法匹配給定字串中數字的出現。

示例

在這個例子中,我們建立了一個包含數字的字串。之後,我們建立了一個帶有 g 標誌的正則表示式,以匹配字串中所有數字的出現,並將其作為match() 方法的引數,在字串中進行匹配。

match() 方法返回一個數組,其中包含根據正則表示式匹配的所有數字。

<html>
   <body>
      <h3>Using the <i> match () </i> Method and Regular Expression to extract the numbers from the string</h3>
      <div id = "output"> </div>
      <script>
         let output = document.getElementById("output");

         // defining the string containing the numbers
         let str = "Sampll323435 Stringrfd23232ftesd3454!";
         output.innerHTML = "Original String: " + str + "<br/>";

         // Matching for the numbers using the match() method.
         let numbers = str.match(/\d+/g);

         // numbers is an array of all occurrences of numbers
         
         // if any single number is available in the string, then print numbers
         if (numbers.length > 0) {
            output.innerHTML += "<br> Numbers in the StringL: " + numbers + "<br/>";
         }
      </script>
   </body>
</html>

使用 replace() 方法和正則表示式

我們可以使用正則表示式來識別數字字元和其他字元。因此,我們將使用正則表示式來識別其他字元,並將其替換為空字串。這樣,我們可以刪除除數字以外的所有字元,並從字串中提取數字。

語法

使用者可以按照以下語法使用replace() 方法從字串中提取數字。

let result = str.replace(/[^0-9]/g,"");

在上面的語法中,str 是我們想要從中提取數字的參考字串。此外,正則表示式[^0-9] 表示所有不在 0 到 9 之間的字元。

示例

在下面的示例中,我們使用了replace() 方法來替換除數字字元以外的所有字元為空字串。我們將正則表示式作為第一個引數,空字串作為第二個引數。

replace() 方法在將除數字字元以外的所有字元替換為空字串後返回字串。在輸出中,我們可以觀察到,它不像match() 方法那樣返回陣列,而只返回單個字串。

<html>
   <body>
      <h3>Using the <i> replace() </i> method and regular expression to extract the numbers from the string</h3>
      <div id = "output"> </div>
      <script>
         let output = document.getElementById("output");
         let string = "dnbdj53454 4k54k6j23in k09e30n9923g9 kjm545";
         output.innerHTML = "Original String: " + string + "<br/>";

         // replace all non-numeric characters with empty string
         let result = string.replace(/[^0-9]/g, "");
         output.innerHTML +="<br> Numbers in the string: " + result + "<br/>";
      </script>
   </body>
</html>

使用 reduce() 方法從字串中提取數字

reduce() 是 JavaScript 的內建庫方法。我們可以將字串轉換為字元陣列,並使用reduce() 方法處理字元陣列。reduce() 方法幫助我們將陣列簡化為單個元素,方法是對陣列元素執行操作。

在這裡,我們將檢查字元是否為數字,並將其新增到最終元素;否則,我們將新增空字串。

語法

使用者可以按照以下語法使用reduce() 方法從字串中提取數字。

let charArray = [...string];
let numbers = charArray.reduce(function (numString, element) {
   let nums = "0123456789";
   if (nums.includes(element)) {
      return numString + element;
   }
   return numString;
},"");

在上面的語法中,我們使用了帶有 charArray 的 reduce 方法。我們將回調函式作為第一個引數,空字串作為第二個引數。

演算法

  • 步驟 1 - 使用擴充套件運算子將字串轉換為字元陣列。

  • 步驟 2 - 使用reduce() 方法和charArray 將整個陣列簡化為僅包含數字的單個字串。

  • 步驟 3 - 將回調函式作為 reduce() 方法的第一個引數傳遞,該函式返回簡化的字串。

  • 步驟 4 - 在回撥函式中,將numString 作為第一個引數傳遞(這是一個簡化的字串),並將 element 作為第二個引數傳遞(這是一個數組元素,即字串的字元)。

  • 步驟 5 - 在回撥函式內部,檢查陣列的字元(即元素)是否在 0 到 9 之間。如果是,則將字元新增到numString 並返回;否則,按原樣返回numString

  • 步驟 6 - 作為reduce() 方法的第二個引數,傳遞一個空字串,它是numString 的初始值。

  • 步驟 7 - 陣列完全迭代後,reduce() 方法返回numString 的最終值。

示例

在下面的示例中,我們獲取了一個包含數字的字串,並實現了上述演算法以從字串中提取數字。

<html>
   <body>
      <h3>Using the <i>reduce() </i>method to extract the numbers from the string</h3>
      <div id = "output"> </div>
      <script>
         let output = document.getElementById("output");
         let string = "34gr345fr45";
         output.innerHTML += "Original String: " + string + "<br/>";
         let charArray = [...string];
         let numbers = charArray.reduce(function (numString, element) {
            let nums = "0123456789";
            if (nums.includes(element)) {
               return numString + element;
            }
            return numString;
         }, "");
         output.innerHTML +="<br> Number in the String: " + numbers + "<br/>";
      </script>
   </body>
</html>

在本教程中,我們討論了三種從給定字串中提取數字的方法。第一種方法是使用match() 方法和正則表示式來搜尋字串中所有數字。第二種方法是使用replace() 方法和正則表示式來刪除字串中所有非數字字元,只留下數字。第三種方法是使用reduce()includes() 方法。重要的是要仔細考慮哪種方法最適合特定情況。

更新於:2023年9月14日

34K+ 次檢視

啟動您的職業生涯

透過完成課程獲得認證

開始學習
廣告
© . All rights reserved.