Home > Software design >  How to check a regex at a specific index in Typescript?
How to check a regex at a specific index in Typescript?

Time:11-10

I am trying to do a regex match at a specific position in Typescript.

Here's what I have tried.

var str = "0123ABC789"
function matchesAt(rgx: RegExp, s : string, i : number) : string | void {
    rgx.lastIndex = i

    console.log(rgx.exec(s));
}

matchesAt(/(ABC)/g, str, 4 )

In essence, I am trying to recreate the String.startsWith(string, number) method, but with a regex inside - instead of another string.

I am expecting that the function should only match when the index is 4. any other number should return a nil.

CodePudding user response:

You can check if matched string length plus i is equal as following lastIndex:

function matchesAt(rgx: RegExp, s : string, i : number) : string | void {
    rgx.lastIndex = i
    let isMatching = rgx.exec(s);

    if (isMatching && isMatching?.length > 1 && rgx.lastIndex - isMatching[1]?.length == i)
        return s;
    return void null;
}

CodePudding user response:

You can use the sticky flag y:

The y flag indicates that the regex attempts to match the target string only from the index indicated by the lastIndex property (and unlike a global regex, does not attempt to match from any later indexes).

function matchesAt(rgx, s, i) {
    rgx.lastIndex = i;
    return rgx.test(s); // use .test to get boolean result
}

var str = "0123ABC789";
console.log(matchesAt(/ABC/gy, str, 4)); // true
console.log(matchesAt(/ABC/gy, str, 3)); // false!

  • Related