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

CF_HoneyBadger
  • 2,960
  • 2
  • 14
  • 16

1 Answers1

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
CF_HoneyBadger
  • 2,960
  • 2
  • 14
  • 16
anubhava
  • 761,203
  • 64
  • 569
  • 643