How to get a value in javascript link

Asked

Viewed 1,369 times

2

Hello! How can I get certain values in a link? I have a url like this: slide.html? title=Volume name=12 but I only want to display the volume value in an H2.

My Code:

$(document).ready(function(){
  var html = '';

  var query = location.search.slice(1);
  var partesDaQuery = query.split("&");
  var json = {};

    partesDaQuery.forEach(function(partes){
      var chaveValor = partes.split('=');
      var paramsKey = chaveValor[0];
      var paramsValue = chaveValor[1];
      json[paramsKey] = paramsValue;

      html += '<h2></h2>';
      console.log(paramsValue);
        });
    $("#lista").html(html);

  });

  • The link is always in this pattern?

  • It is. It will keep that way.

1 answer

4


There are several ways to catch the string, one of them is using split('=').pop() if the string you want to capture from the URL is always the last one after the =:

URL of the page: slide.html?titulo=Nome&volume=12

var string = location.href.split("=").pop();

The result of string is 12.

An example as if local were the page URL:

local = "slide.html?titulo=Nome&volume=12"; // apenas para exemplo

var string = local.split("=").pop();

alert(string);

Another way with lastIndexOf:

var url_ = location.href;
var string = url_.substring(url_.lastIndexOf("=")+1,url_.length);

Example:

local = "slide.html?titulo=Nome&volume=12";

var string = local.substring(local.lastIndexOf("=")+1,local.length);

alert(string);

Take any parameter:

var url_ = new URL(location.href);
var string = url_.searchParams.get("volume");

If you want to take another parameter, just change volume in url_.searchParams.get("volume");

  • It worked. Vlw. And in case I just want to take the title?

  • @Oliverdamon I put at the end of the answer. Thanks!

  • Vlw. Helped a lot, bro.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.