Reputation: 69
I'm new to regex and trying to get number after substring text
and before first non-numeric value.
I have:
const str = 'fasdfsdanvczx fdasvczx text 321,fasdgasdf';
str.toLowerCase().match(new RegExp('text (.*)[^0-9]'));
As a result I'm receiving:
["text 321,fasdgasdf", "321,fasdgasd"]
but I want only 321
.
Thanks in an advance for any help.
Upvotes: 2
Views: 387
Reputation: 163207
You could match the digits only in the first capturing group and use word boundaries \b
to prevent text
and the digits being part of a larger word.
Note to double escape the backslashes when using the RegExp constructor.
\btext (\d+)\b
const str = 'fasdfsdanvczx fdasvczx text 321,fasdgasdf';
let res = str.toLowerCase().match(new RegExp('\\btext (\\d+)\\b'));
console.log(res[1]);
Upvotes: 3
Reputation: 520908
You may try splitting twice:
var str = 'fasdfsdanvczx fdasvczx text 321,fasdgasdf';
var num = str.split(/text /)[1].split(/\D/)[0];
console.log(num);
The first spiit leaves us with 321,fasdgasdf
, and the second split discards everything from the comma onwards.
Upvotes: 0
Reputation: 1837
Use lookbehind to find number after 'text ':
(?<=text )\d+
Or simply match parts and select second group:
(text )(\d+)
Upvotes: 1