Problems with indexOf and lastIndexOf on a substring - Get part of a URL from a string

I have a few problems that break the string the way I want. I have a url:

http://SomeAddress.whatever:portWhatever/someDirectory/TARGETME/page.html 

I am trying to get the TARGETME part in a string using substring and indexOf instead of regex. This is the function I'm working with now:

  function lastPartofURL() { // Finding Url of Last Page, to hide Error Login Information var url = window.location; var filename = url.substring(url.lastIndexOf('/')+1); alert(filename); } 

However, when I wrote this, I aimed at the "page.html" part to return, but it is difficult for me to reconfigure it to do what I want it to do now.

If possible, I would like it to start at the beginning of the line, and not end, as there should always be a URL and then one directory before what I'm trying to configure, but I'm interested in both solutions.

Here is a regular expression that does something similar, but it is not protected (according to JSLint), and therefore I would not refuse to replace it with something more functional.

  /^.*\/.*\/TARGETME\/page.html.*/ 
+6
source share
4 answers

As others have said, .split() is good for your business, however it is assumed that you want to return the "part to the last" URL (for example, return "TARGETME" for http://SomeAddress.whatever:portWhatever/dirA/DirB/TARGETME/page.html ), then you can’t use a fixed number, but rather take the element to the last from the array:

 function BeforeLastPartofURL() { var url = window.location.href; var parts = url.split("/"); var beforeLast = parts[parts.length - 2]; //keep in mind that since array starts with 0, last part is [length - 1] alert(beforeLast); return beforeLast; } 
+6
source

You can make it easier with string.split() ...

 function getPath() { var url = window.location; var path = url.split("/")[4]; alert(path); return path; } 

I suggest this method only because you always know the URL format.

+2
source
  function lastPartofURL() { // Finding Url of Last Page, to hide Error Login Information var url = window.location; var arr = url.split('/'); alert(arr[4]); } 

Look here

+1
source

try it

  function lastPartofURL() { // Finding Url of Last Page, to hide Error Login Information var url = window.location; var sIndex = url.lastIndexOf('/'); var dIndex = url.lastIndexOf('.', sIndex); if (dotIndex == -1) { filename = url.substring(sIndex + 1); } else { filename = url.substring(sIndex + 1, dIndex); } alert(filename); } 
+1
source

All Articles