2017-04-24 12 views
0

ユーザーが入力したパスを分割し、その一部を取得する必要があります。例えば、ユーザーのようにパスを入力した場合:URLパスを分割して2つの部分だけを取得する

4月/ abc.jpg

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

私はそれを取得する必要があります

$(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

基本的にファイル名と親フォルダのみが必要ですか? –

+0

明確な答えを出すのは難しいです。この例ではさらに多くの質問を提供します。イメージの後のパスだけを意味しますか?最後の2人の子供だけを意味しますか? – manuzi1

+1

[jQueryのURLパスを分割してその一部を取得する]の可能な複製(http://stackoverflow.com/questions/43533945/splitting-a-url-path-in-juery-and-getting-a-part –

答えて

1

split()配列を返します。分割した後、あなたは次のようにその中の任意の部分を取得することができます:

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

 
    var split = imgPath.split('/'); 
 
    
 
    var desiredPath = split[split.length-2] + "/" + split[split.length-1]; 
 
    
 
    console.log(desiredPath); 
 
    }); 
 
});
<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>

2

あなたがsplitを使用する場合、それはarrayにデータを分割します。次に、array[number]を使用して特定の値を取得することができます。

$(document).ready(function(){ 
 
    $('#getData').click(function(){ 
 
    imgPath = $('#imgPath').val(); 
 
    var s = imgPath.split('/'); 
 
    var l = s.length - 1; 
 
    console.log(s[(l - 1)] + "/" + s[l]); 
 

 
    //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>

2
あなたは、分割後の最後から値を取得するためにポップを使用することができます

str = '/content/mypath/myfolder/about/images/April/abc.jpg'; 
 
var a = str.split('/'); 
 
second = a.pop(); 
 
first = a.pop(); 
 
url = first+"/"+second; 
 
console.log(url);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

EDIT:

あなたは、より最適化された方法を持つことができ

str = '/content/mypath/myfolder/about/images/April/abc.jpg'; 
 
    var a = str.split('/'); 
 
    arr = []; 
 
    arr.push(a.pop(),a.pop()); 
 
    str = arr.reverse().join("/"); 
 
    console.log(str);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

利点:(あなたがしたい場合)。このように

は、あなたが二つ以上を持つことができるの最後の側から2つ以上の部分を達成するための柔軟性を提供します。

こちらがお役に立てば幸いです。

関連する問題