0

I'm looking for a javascript replace regex that will strip out everything but the first number in a string. (The last will also work as well, see my test cases below)

Given the following:

P1, PROTECTED 1
or
P3, PROTECTED 3
or
P10, PROTECTED 10

I need 1,3, or 10

I need to only return the first or last number. It'll be between 1 and 10. They're the same.

var foo = 'P10, PROTECTED 10';
foo.replace(/(\d+)/,'');

strips out the first number...I need the exact opposite

2
  • 1
    Search using /^\D*(\d+).*/ and replace with $1 Commented Sep 1, 2022 at 20:09
  • 1
    OP wants a replace not match here. There might be better dupe link but not this one. Commented Sep 2, 2022 at 5:53

1 Answer 1

2

You can search using this regex:

^\D*(\d+).*

and replace with '$1' (capture group #1)

RegEx Demo

Code:

const arr = ['P1, PROTECTED 1',
'P3, PROTECTED 3',
'P10, PROTECTED 10'];

const re = /^\D*(\d+).*/m;

arr.forEach(el => console.log(el.replace(re, '$1')));

RegEx Breakup:

  • ^: Start
  • \D*: Match 0 or more non-digits
  • (\d+): Match 1+ digits in capture group #1
  • .*: Match everything till line end
Sign up to request clarification or add additional context in comments.

1 Comment

foo= foo.replace(/^\D*(\d+).*/, '$1'); seems to have done it. thanks a lot!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.