Issue
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.
Solution
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 thelastIndex
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!
Answered By - trincot
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.