The problem with ^(?<=foo:)\d+
pattern is that ^
matches the start of the string and (?<=foo)
lookbehind fails the match if there is no foo
immediately to the left of the current location - and there is no text before the start of the string.
You could fix it as
const regex = new RegExp(/(?<=^foo:)\d+/);
Here, (?<=^foo:)
lookbehind checks for foo
at the start of the string, but tests each location in the string since ^
is no longer the part of the consuming pattern.
In JS, for better portability across browsers, you'd better use a capturing group rather than a positive lookbehind (and also, you may directly use the regex literal notation, no need to use /.../
with constructor notation):
var str = "foo:25"
var regex = /^foo:(\d+)/;
console.log(regex.exec(str)[1]);