簡體   English   中英

從 Javascript 中的字符串中查找數字索引

[英]Find index of numbers from a string in Javascript

我想在下面的字符串中獲取數字索引( 1994 和 27 )

我試圖拆分字符串,但不知道之后該怎么做

let str = 'year of birth: 1994, and i'm 27 yo'

查找索引的簡單方法

function findindex(str) {
        var num = /\d/;
        var nums = str.match(num);
        return str.indexOf(nums);
    }

console.log(findindex('year of birth: 1994'));//將是16

拆分字符串后。 只需循環並檢查該值是否為數字。

let str = "year of birth : 1994 , and i'm 27 yo";
strArray = str.split(' ');
    for(let i=0;i<strArray.length;i++){
        //Use isNaN() to check if the value is a number.
        if(isNaN(strArray[i])==false){
            console.log("Number "+strArray[i]+" is at index "+i);
        }
    }

一種方便快捷的方法是嘗試search()

語法是:

海峽搜索(正則表達式);

其中 ( str ) 是要搜索的字符串。 ( regex ) 是您要搜索的內容。

返回值:是你所追求的事物第一次出現的索引,在你的例子中,是一個數字。 從這里開始,由您決定如何處理該索引 即:從這個索引開始切片你的字符串,也許?

使用此方法的一個重要關鍵是對正則表達式行業有足夠的了解,這超出了您問題的scope。

你的例子:

 let str = "year of birth: 1994, and i'm 27 yo"; let reg = /\d/; let ind = str.search(reg); alert('the first instance of "'+reg+'" is found at index: ' + ind); // expected result is 16, as it is the index of the number (1) in 1994; //if you want a certain number (not just any number), you //can modify the reg variable. Let's search for 94, for example.. reg = /94/; ind = str.search(reg); alert('the first instance of "'+reg+'" is found at index: ' + ind);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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