2017-04-21 8 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')となります。これは無効です。したがって、エラーです。

あなたは正規表現は任意の数の文字が続くimages/と一致します画像パス

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

を取得するために正規表現を使用することができます。 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

私は最後の2つのパス値が必要と仮定しています。

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

これはすいません.... – Vbudo

関連する問題