Skip to content Skip to sidebar Skip to footer

Splitting A Url Path In Jquery And Getting A Part Of It

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 di

Solution 1:

$(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]);
  });
});
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
Image path: <inputtype="text"id="imgPath"value="/content/mypath/myfolder/about/images/abc.jpg"><buttonid="getData">Click</button>

Solution 2:

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 pathvar shortPath = theArray[theArray.length - 2] + '/' + 
                 theArray[theArray.length - 1];


      });
});

Solution 3:

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).

Post a Comment for "Splitting A Url Path In Jquery And Getting A Part Of It"