0 votes

Select the part of the pathname

I want to get a text of the pathname, for example if the link is https://es.stackoverflow.com/questions/ask I would like to be able to simply get the questions or the ask.

function seleccionar() {
  var pathnam = window.location.pathname;
  document.getElementById("path").innerHTML = pathnam;
}
#path{
color: #fff;
padding: 5px;
background-color: red;
}
<div id="path"></div>
<button onclick="seleccionar()">Obtener</button>

0voto

Marcos Points 15902

To obtain the various parts of the path you could use String.split()

Example:

function seleccionar() {
  var pathnam = window.location.pathname;
  var parts = pathnam.substr(1).split('/');
  document.getElementById("path").innerHTML = JSON.stringify(parts);
}
#path{
color: #fff;
padding: 5px;
background-color: red;
}
<div id="path"></div>
<button onclick="seleccionar()">Obtener</button>

On time:

  • For the case window.loaction.href = 'https://es.stackoverflow.com/questions/ask'
  • You'll get parts = ["questions", "ask"]
  • To recover "questions" it would be sufficient to use parts[0]

HolaDevs.com

HolaDevs is an online community of programmers and software lovers.
You can check other people responses or create a new question if you don't find a solution

Powered by:

X