2016-11-09 60 views
0

之間的字符串我有這個網址:https://www.tripadvisor.com/img/cdsi/img2/ratings/traveler/3.5-27451-5.png如何提取斜槓

我試圖捕捉值「3.5」,這是位於最後一個斜槓之後和第一個破折號前。

我以爲我可以像這樣實現它:

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

,但沒有運氣。任何幫助將非常感激。我怎樣才能做到這一點?

+1

它的工作原理,如果你使用正確的引號: '/img/cdsi/img2/ratings/traveler/3.5-27451-5.png'。 。分裂( '/')POP()分割( ' - ')移位(); – Danmoreng

回答

2

可以使用Regular Expressions捕捉到它。

在常規表達式...

  1. 點(.)表示任意字符

  2. \w表示字母數字字符(a到z,A至Z和0到9)和下劃線(_

  3. 加(+)說,至少有一個字符

    .+任何字符改一次,[a-z]+ a至z至少一次,\w+任何字母數字至少一次。

  4. ?)停止正則表達式變得貪婪

  5. -)無非是應該出現在您的網址

這裏一個簡單的人物,我們有三個部分:

  1. 。+/:捕捉到https://www.tripadvisor.com/img/cdsi/img2/ratings/traveler/

  2. :捕捉3.5

  3. - (+?)。+:捕捉-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]);

2

您正在使用錯誤的引號。

變化:

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

要:

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

好抓!我錯過了。 :) – sam