0

How do I extract the number inside of a string like the examples below?

myform-5-id
myform-32-id
myform-0-id

The number will always be an integer >= 0, and the text will always be the same.

Ben
  • 17,762
  • 27
  • 102
  • 166

3 Answers3

2

The regex that you are looking for is /\d+/.

Regex Explanation:

  • \d+ matches one or more numbers
  • The surrounding / is the way to mention the regex pattern

Working Code Snippet:

var r = /\d+/;
var s = "myform-5-id";
alert (s.match(r));

Demo on Regex101 with explanation

Source

Community
  • 1
  • 1
Rahul Desai
  • 14,618
  • 18
  • 81
  • 134
0

Use parseInt();

var int= parseInt('myform-5-id'.match(/[0-9]+/), 10);
alert(int);

This is an actual number and not a string.

rrr
  • 2,480
  • 4
  • 27
  • 33
0

If you want a non regex solution than you can use this otherwise @Rahul answer is perfect

var a="myform-5-id";
var res=a.split('-');
alert(res[1]);
Muhammad Bilal
  • 2,056
  • 1
  • 15
  • 23