Splitting a URL path in jQuery and getting a part

2019-07-31 01:29发布

I need to split the path entered by the user and grab only certain part of it. For e.g. if the use enters path as:

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

Then I want to display only images/abc.jpg.

I'm getting

Uncaught Error: Syntax error, unrecognized expression

error at the moment.

Here's my code.

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

3条回答
孤傲高冷的网名
2楼-- · 2019-07-31 01:48

$(imgPath) will try to locate the element where imgPath is selector. As the Path entered by user is not correct selector, it'll throw error. Example, if user entered /content/mypath/myfolder/about/images/abc.jpg the selector will be $('/content/mypath/myfolder/about/images/abc.jpg') which is not valid express, thus the error.

You may use RegEx to get the image path

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

The regex will match images/ followed by any number of characters. match returns an array, so using [0] will get the image path.

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

查看更多
对你真心纯属浪费
3楼-- · 2019-07-31 01:52

You should use console.log(imgPath.split("/")) instead of console.log($(imgPath).split("/")).

Here imgPath is just a variable that stores the input value and not a dom element to be used as $(imgPath).

查看更多
一夜七次
4楼-- · 2019-07-31 01:56

I'm assuming to want the last two path values.

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


      });
});
查看更多
登录 后发表回答