使用location.search定位参数的值 [英] Using location.search to locate a parameter's value
问题描述
我正在开发一个工具,它接受网址中的值参数,然后用它们做一些事情。
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
-
location.search
将等于?name = jon& country = us
- '。slice(1)'跳过'?',返回字符串的其余部分。
3.split(&)[0]
将其拆分为两个字符串(?name = jon
和country = us
)并取第一个 -
.split(=)[1 ]
将name = jon
拆分为name
和jon
并采取第二个。完成!
location.search
will be equal to?name=jon&country=us
- '.slice (1)' skips the '?', returning the rest of the string.
3
.split("&")[0]
splits it into two strings (?name=jon
andcountry=us
) and takes first one .split("=")[1]
splitsname=jon
intoname
andjon
and takes the second one. Done!
这篇关于使用location.search定位参数的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!