Your main issue is that you quoted the expression. The String
prototype does not have a match
method. It needs to be a regex literal or RegExp
object.
You can use a positive look-behind (?<=_text)
and a positive look-ahead (?=_)
and wrap the expression [^_]*
(zero or more non-underscores).
You can extract the first match with destructuring the result array.
const str = 'line0_text4_89yf9sd9afg977f8gds9g9fdg';
const regexToGetNumber = /(?<=_text)[^_]*(?=_)/gm;
const [value] = str.match(regexToGetNumber) ?? [];
console.log(value); // '4'
If you have a regex string, you need to call the RegExp
constructor:
const str = 'line0_text4_89yf9sd9afg977f8gds9g9fdg';
const regexToGetNumber = new RegExp('(?<=_text)[^_]*(?=_)', 'gm');
const [value] = str.match(regexToGetNumber) ?? [];
console.log(value); // '4'