NewCodeMan NewCodeMan - 3 years ago 160
Javascript Question

How to extract specific data from a string of text

Is there a way to use JavaScript to remove unwanted data. For example in this address:

url("assets/images/films/deor/films_deor_ip_full_1.jpg")


I want to create a variable with only the "1" as the value.

Its used for a picture viewer, scrolling to the next image. So the entire string always stays the same except for the number. I want to be able to grab that number anytime and place in a variable.

Answer Source

I'd use a regular expression to extract the number, for example:

var url = "assets/images/films/deor/films_deor_ip_full_1.jpg";
var regex = /_(\d+)\.jpg$/i;
var imgNumber = parseInt(regex.exec(url)[1], 10);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download