0

Using javascript -- I need to pull out and examine the number that appears just before the "jpg" file extension, in this case "300".

var filename = 2012_honda_odyssey_passenger-minivan_ex_s_oem_2_300.jpg

What's the best way to pull this number out -- I can alway assume it will be between the last "_" in the string and this final "." before the file extension.

I'm guessing that I need to do something with regex. Like this ....

var num = parseInt(filename.match(/some-regex-here/), 10);

addition

I did come up with this ... but it seemed very kludgy.

var filename = "2012_honda_odyssey_passenger-minivan_ex_s_oem_2_300.jpg";
var num = parseInt(filename.split('_').splice(-1,1).toString().split(".").splice(0,1).toString(), 10);
rsturim
  • 6,756
  • 15
  • 47
  • 59
  • See me answer to [this question](http://stackoverflow.com/questions/12626898/jquery-regex-to-parse-image-name/12627019#12627019). It's pretty much the same thing. – Martin Ender Sep 28 '12 at 05:35

6 Answers6

1
var filename = "2012_honda_odyssey_passenger-minivan_ex_s_oem_2_300.jpg";
var regex = /^.*_(\d+)\.jpg?$/;
var match = regex.exec(filename);
var number = Number(match[1]);

console.log(number);
driangle
  • 11,601
  • 5
  • 47
  • 54
0

A regular expression such as this: _(\d+)\..+?$ should allow you to match and extract the number to a group. The regex above should match an underscore (_) followed by one ore more digits (\d+), followed by a period (\.) which in turn is followed by some letters (.+?) and finally the end of the string ($).

You can then refer to this previous SO question to see how you can later access these groups.

Community
  • 1
  • 1
npinti
  • 51,780
  • 5
  • 72
  • 96
0
var num=parseInt(filename.replace(/^.*?([0-9]+).jpg$/i,"$1"),10);
Passerby
  • 9,715
  • 2
  • 33
  • 50
0

Avoiding regexes is usually best, unless you're doing complex string pattern matching is usually. Something like will get what you want:

var num = +filename.substring(
  filename.lastIndexOf('_') + 1,
  filename.lastIndexOf('.')
);
Paul
  • 139,544
  • 27
  • 275
  • 264
0

try this:

'2012_honda_odyssey_passenger-minivan_ex_s_oem_2_300.jpg'.match(/[0-9]+(?=\.jpg)/)[0]
turtledove
  • 25,464
  • 3
  • 23
  • 20
-1

I feel a regex is overkill for something this simple, I would just use this:

var start = filename.lastIndexOf('_') + 1; 
var end = filename.lastIndexOf('.');
var num = parseInt(filename.substring(start, end), 10);
verdesmarald
  • 11,646
  • 2
  • 44
  • 60
  • I feel eventhough this is an acceptable answer to the situation where the OP is. It doesn't answer the real question "how to pull a number out of regex ? ". Can you please edit the answer to help people who came here actually looking for a way to parse the number from a string. @ggreiner 's answer seems closer. – Vasif Jul 28 '16 at 23:41