NewCodeMan
NewCodeMan

Reputation: 227

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.

Upvotes: 0

Views: 613

Answers (2)

ncardeli
ncardeli

Reputation: 3492

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);

Upvotes: 1

clabe45
clabe45

Reputation: 2454

I don't think you need to strip the unwanted data away, but rather retrieve the wanted data. You can do this because you know at what index the integer will occur.

Here's an example:

let startIdx = "assets/images/films/deor/films_deor_ip_full_".length();
let endIdx = str.length()-".jpg".length();
let theInt = parseInt(str.substring(startIdx, endIdx));

Sidenote:

I want to be able to grab that number anytime and place in a variable.

Concerning the second part, in JavaScript, strings are immutable, meaning you cannot change them after you create them.

Upvotes: 1

Related Questions