Using location.search to locate a parameter's value

和自甴很熟 提交于 2019-12-06 04:34:28

问题


I’m working on a tool which takes the value parameters in the URL and does a few things with them.

My issue is, I can’t seem to use document.location to show the specific value that I’m after, for example:

www.examplesite.com?yourname=gilgilad

I want to use document.location.search and put it in a var, I need that var's value to be "gilgilad".

Is this even possible using location.search?


回答1:


location.search will return all after question mark including it. So there is universal js to get value of the first parameter (even if url has more parameters):

var desire = location.search.slice(1).split("&")[0].split("=")[1]

Example: let's take url http://example.com?name=jon&country=us

  1. location.search will be equal to ?name=jon&country=us
  2. '.slice (1)' skips the '?', returning the rest of the string. 3 .split("&")[0] splits it into two strings (?name=jon and country=us) and takes first one
  3. .split("=")[1] splits name=jon into name and jon and takes the second one. Done!



回答2:


A more generic solution to split the location.search query parameters and convert them into an object:

var a = location.search.split("&");
var o = a.reduce(function(o, v) {
    var kv = v.split("=");
    kv[0] = kv[0].replace("?", "");
    o[kv[0]] = kv[1];
    return o;
    },
{});



回答3:


let url = new URL('www.examplesite.com?yourname=gilgilad');
let searchParams = new URLSearchParams(url.search);
console.log(searchParams.get('yourname'));

you can consider also to user window.location or window.location.search directly

let searchParams = new URLSearchParams(window.location.search);
console.log(searchParams.get('yourname'));



回答4:


To make ?yourname=gilgilad using document.location.search:

window.location.search = 'yourname=gilgilad';

here is jsfiddle: http://jsfiddle.net/t81k3bgc/

make sure to use console and then [run]. you will see:

For more information: https://developer.mozilla.org/en-US/docs/Web/API/Window.location#Example_.235.3A_Send_a_string_of_data_to_the_server_by_modifying_the_search_property.3A



来源:https://stackoverflow.com/questions/26803110/using-location-search-to-locate-a-parameters-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!