Query string parameters have been incredibly useful on the server side since the internet took liftoff, but it wasn't until AJAX-driven web apps became popular that we relied too much on them on the client side. Not only do we grab parameter values but we also modify them dynamically with the History API, so these parameters play a major role outside of the initial page load.
自从互联网问世以来,查询字符串参数在服务器端已经非常有用,但是直到AJAX驱动的Web应用程序变得流行之后,我们才在客户端大量依赖它们。 我们不仅可以获取参数值,还可以使用History API动态修改它们,因此这些参数在初始页面加载之外起着重要作用。
We've always been able to get the full query string via the window.location.search property:
我们始终能够通过window.location.search属性获取完整的查询字符串:
console.log(window.location.search); // "?post=1234&action=edit"...but in a world of setters, getters, and JSON, there must be a better way to get values than parsing a string, right? After years of ugly string parsing, there's a better way: URLSearchParams Let's have a look at how we can use this new API to get values from the location!
...但是在setter,getter和JSON的世界中,必须有比解析字符串更好的获取值的方法,对吗? 经过多年丑陋的字符串解析后,有一种更好的方法: URLSearchParams让我们看看如何使用这个新的API从该位置获取值!
// Assuming "?post=1234&action=edit" var urlParams = new URLSearchParams(window.location.search); console.log(urlParams.has('post')); // true console.log(urlParams.get('action')); // "edit" console.log(urlParams.getAll('action')); // ["edit"] console.log(urlParams.toString()); // "?post=1234&action=edit" console.log(urlParams.append('active', '1')); // "?post=1234&action=edit&active=1"URLSearchParams also provides familiar Object methods like keys(), values(), and entries():
URLSearchParams还提供了熟悉的Object方法,例如keys() , values()和entries() :
var keys = urlParams.keys(); for(key of keys) { console.log(key); } // post // action var entries = urlParams.entries(); for(pair of entries) { console.log(pair[0], pair[1]); }URLSearchParams reminds me a lot of the classList API -- very simple methods yet very useful.
URLSearchParams让我想起了很多classList API-非常简单的方法,但非常有用。
While URLSearchParams is ideal, not all browsers support that API. There's a polyfill available but if you want a tiny function for basic query string parsing, the following is a function stolen from the A-Frame VR toolkit which parses the query string to get the key's value you'd like:
虽然URLSearchParams是理想的选择,但并非所有浏览器都支持该API。 有一个polyfill,但是如果您想要一个用于基本查询字符串解析的小函数,则以下是从A-Frame VR工具箱中窃取的函数,该工具会解析查询字符串以获取您想要的键值:
function getUrlParameter(name) { name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]'); var regex = new RegExp('[\\?&]' + name + '=([^]*)'); var results = regex.exec(location.search); return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' ')); };With the function above, you can get individual parameter values:
使用上面的函数,您可以获得单个参数值:
getUrlParameter('post'); // "1234" getUrlParameter('action'); // "edit"Anyways, enjoy this function -- you'll find yourself needing it more than you think!
无论如何,请享受此功能-您会发现自己比想象中需要的更多!
翻译自: https://davidwalsh.name/query-string-javascript