简体   繁体   中英

How can I extract a dynamic number from a dynamic url-string in Javascript?

I have to extract some value from an url which might differ in the following ways. Possible combinations are:

www.example.com/liveDetail/1
www.example.com/liveDetail/22
www.example.com/liveDetail/1?language=en
www.example.com/liveDetail/1?language=en&size=5

What I want is to get the number after 'liveDetail/' . But this number might differ in length and the url might or might not have some other parameters after it. These parameters might contain numbers, too, which I'm not interested in.

Is there any way of doing so with plain Javascript or by using a regex-expression (I already tried some things but only succeeded in deleting the first part of it)?

It seems like you just want to capture the first number after the slash, so

let url = "www.example.com/liveDetail/1";
let number = url.match("\/\d+").substring(1);

This captures the slash and any number afterwards, and then removes the slash from the captured value.

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