2017-04-21 101 views
1

我需要拆分用戶輸入的路徑,並只抓取它的某個部分。 例如如果使用的路徑爲:在jQuery中拆分URL路徑並獲取其中的一部分

/content/mypath/myfolder/about/images/abc.jpg 

然後我只想顯示images/abc.jpg

我越來越

Uncaught Error: Syntax error, unrecognized expression

錯誤的時刻。

這裏是我的代碼。

$(document).ready(function(){ 
 
    $('#getData').click(function(){ 
 
    imgPath = $('#imgPath').val(); 
 

 
    console.log($(imgPath).split('/')); 
 

 
    //console.log(slicedPath); 
 
    }); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script> 
 
Image path: <input type="text" id="imgPath"> 
 
<button id="getData">Click</button>

+0

'.val()'返回一個字符串,而不是DOM元素。要求jQuery包裝它不會起作用。只需使用'imgPath.split('/')' – Tibrogargan

+0

獲取最後一部分的標準是什麼?你正在尋找某個單詞(即「圖像」)還是你在一個文件和直接父母之後? – Tibrogargan

+0

最後一部分應該只是一個圖像名稱,後跟圖像擴展名。 – Sunny

回答

1

$(imgPath)會試着找到其中imgPath是選擇的元素。由於用戶輸入的路徑不正確,它會引發錯誤。 例如,如果用戶輸入/content/mypath/myfolder/about/images/abc.jpg,則選擇器將爲$('/content/mypath/myfolder/about/images/abc.jpg'),這是無效的,因此是錯誤。

您可以使用正則表達式來獲得圖像路徑

imgPath.match(/images\/.*$/i)[0] 

正則表達式匹配images/後跟任意數量的字符。 match返回一個數組,因此使用[0]將獲得圖像路徑。

$(document).ready(function() { 
 
    $('#getData').click(function() { 
 
    var imgPath = $('#imgPath').val(); 
 

 
    console.log(imgPath.match(/images\/.*$/i)[0]); 
 
    }); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script> 
 
Image path: <input type="text" id="imgPath" value="/content/mypath/myfolder/about/images/abc.jpg"> 
 
<button id="getData">Click</button>

-1

您應該使用console.log(imgPath.split("/"))而不是console.log($(imgPath).split("/"))

這裏imgPath只是一個變量,它存儲輸入值,而不是用作$(imgPath)的dom元素。

+0

這是我希望的正確解釋! –

1

我假設想要最後兩個路徑值。

$(document).ready(function(){ 
    $('#getData').click(function(){ 
    imgPath = $('#imgPath').val(); 

var theArray = imgPath.split('/'); // split path into parts 

// take the last two indexes to form short path 
var shortPath = theArray[theArray.length - 2] + '/' + 
       theArray[theArray.length - 1]; 


     }); 
}); 
+0

或更簡潔:'theArray.split(-2).join('/')' – Tibrogargan

+0

這是supa .... – Vbudo