简体   繁体   中英

How to extract a string between a forward slash

I have this URL: https://www.tripadvisor.com/img/cdsi/img2/ratings/traveler/3.5-27451-5.png

I am trying to capture the value "3.5", which is located after the last forward slash and before the 1st dash.

I thought I could achieve it with something like this:

‘/img/cdsi/img2/ratings/traveler/3.5-27451-5.png'.split('/').pop().split(‘-‘).shift();

But no luck. Any help would be much appreciated. How can I do this?

You're using the wrong quotation marks.

Change:

‘/img/cdsi/img2/ratings/traveler/3.5-27451-5.png'.split('/').pop().split(‘-‘).shift();
^                                                                        ^ ^

To:

'/img/cdsi/img2/ratings/traveler/3.5-27451-5.png'.split('/').pop().split('-').shift();

You can capture it using Regular Expressions .

In a regular expression...

  1. the dot ( . ) represents any character

  2. \\w represents alpha numeric characters (a to z, A to Z and 0 to 9) and underscore( _ )

  3. plus ( + ) says at least one character

    .+ any character alteast one time, [az]+ a to z atleast one time, \\w+ any alpha numeric character atleast once.

  4. ( ? ) stops the regex from becoming greedy

  5. ( - ) is nothing but a simple character supposed to be present in your url

Here, we have three parts:

  1. .+/ : capturing until https://www.tripadvisor.com/img/cdsi/img2/ratings/traveler/

  2. (.+?) : capturing 3.5

  3. -.+ : capturing -27451-5.png

 var url = "https://www.tripadvisor.com/img/cdsi/img2/ratings/traveler/3.5-27451-5.png"; //regular expression var reg = new RegExp('.+/(.+?)-.+'); //executes your regular expression var res = reg.exec(url); // result will be captured in res[1] console.log(res[1]); 

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