简体   繁体   中英

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM