简体   繁体   中英

TypeScript - matchAll() function not working

I am working on a VS Code extension, and I need to get the starting index of all occurrences in a line (string). For example, the string can look like this:

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

and, I am trying to match all occurrences of Time with this regular expression:

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

I tried using the matchAll function, in order to check its output:

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

Initially, I got this error:

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.

Thus, I opened tsconfig.json , and updated it (the target library was es2019 initially):

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

After making this small change, the error is now gone, but I am not getting any output to the console. Additionally, it seems that the line where I use matchAll is breaking the TypeScript logic; however, there's no error message displayed for me to see what's wrong with the code.

How can I solve this?

matchAll requires a global regex as an argument:

The RegExp object must have the /g flag, otherwise a TypeError will be thrown.

Try replacing your regex with:

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

or a plain regexp string:

let re = /\bTime\b/g;

除了需要g标志外, matchAll返回一个迭代器,因此请尝试,例如

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM