簡體   English   中英

TypeScript - matchAll() 函數不起作用

[英]TypeScript - matchAll() function not working

我正在開發 VS Code 擴展,我需要獲取一行(字符串)中所有出現的起始索引。 例如,字符串可能如下所示:

let str = "Timei = Time / Day / Time";

並且,我試圖用這個正則表達式匹配所有出現的Time

let re = new RegExp("\\bTime\\b");

我嘗試使用matchAll函數,以檢查其輸出:

console.log(str.matchAll(re));

最初,我收到此錯誤:

Property 'matchAll' does not exist on type 'string'. Do you need to change your target library? Try changing the 'lib' compiler option to 'es2020' or later.

於是,我打開了tsconfig.json並更新了它(目標庫最初是es2019 ):

{
    "compilerOptions": {
        ...
        "target": "es2020",
        "lib": ["ES2020"],
        ...
    },
    ...
}

做了這個小小的改變后,錯誤現在消失了,但我沒有得到任何輸出到控制台。 此外,我使用matchAll的行似乎打破了 TypeScript 邏輯; 但是,沒有顯示錯誤消息讓我查看代碼有什么問題。

我該如何解決這個問題?

matchAll需要一個全局正則表達式作為參數:

RegExp 對象必須具有 /g 標志,否則將拋出 TypeError。

嘗試將您的正則表達式替換為:

let re = new RegExp("\\bTime\\b", "g");

或一個普通的正則表達式字符串:

let re = /\bTime\b/g;

除了需要g標志外, matchAll返回一個迭代器,因此請嘗試,例如

console.log(...str.matchAll(re));

暫無
暫無

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

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