使用location.search定位参数的值 [英] Using location.search to locate a parameter's value

查看:195
本文介绍了使用location.search定位参数的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个工具,它接受网址中的值参数,然后用它们做一些事情。

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

我的问题是,我似乎无法忍受使用document.location来显示我所追求的特定值,例如:

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

我想使用document.location.search并将其放在var中,我需要将var的值设为gilgilad。

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

这是否可以使用location.search?

Is this even possible using location.search?

推荐答案

location.search 将在包含它的问号后返回所有问题。所以有通用的js来获取第一个参数的值(即使url有更多的参数):

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]

示例:让我们拿网址 http://example.com?name=jon&country=us


  1. location.search 将等于?name = jon& country = us

  2. '。slice(1)'跳过'?',返回字符串的其余部分。
    3 .split(&)[0] 将其拆分为两个字符串(?name = jon country = us )并取第一个

  3. .split(=)[1 ] name = jon 拆分为 name jon 并采取第二个。完成!

  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!

这篇关于使用location.search定位参数的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆