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...
the dot ( .
) represents any character
\\w
represents alpha numeric characters (a to z, A to Z and 0 to 9) and underscore( _
)
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.
( ?
) stops the regex from becoming greedy
( -
) is nothing but a simple character supposed to be present in your url
Here, we have three parts:
.+/ : capturing until https://www.tripadvisor.com/img/cdsi/img2/ratings/traveler/
(.+?) : capturing 3.5
-.+ : 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.