Nick Ginanto
Nick Ginanto

Reputation: 32130

Can't capture match in javascript regex

I am having a problem with capture groups in regex in javascript

I have strings such as p4124, p74354, p10, etc... which I want to extract the numbers only.

my regex is /^p(\d+)/g

if I do

str = p4124
str.match(patt)

I get ["p4124"]

How can I get the captured match (to return 4124)?

Upvotes: 0

Views: 227

Answers (3)

Casimir et Hippolyte
Casimir et Hippolyte

Reputation: 89557

You have access to the different capture groups with that:

var str = "p4124";
alert(/^p(\d+)/.exec(str));

first: the whole pattern

second: the capture group

Upvotes: 0

A J
A J

Reputation: 2140

if the pattern is going to be the same (get rid of all non numbers), then you could use the following:

    var thestring = "p123";
    var thenum = thestring.replace(/^\D+/g, '');
    alert(thenum);

Let me know if it worked for you.

Upvotes: 1

jfriend00
jfriend00

Reputation: 707406

Remove the g flag from your regex and you will get the normal matches returned.

The g flag is used in this context for repeated calls on the same regex which is not what you are trying to do here.

Upvotes: 2

Related Questions