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
  • 20,038
  • 30
  • 112
  • 189

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
  • 15,242
  • 19
  • 83
  • 138
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
  • 3,509
  • 4
  • 29
  • 38
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,106
  • 1
  • 15
  • 24