主页 Swift UNIX C Assembly Go Plan 9 Web MCU Research Non-Tech

How to get query of URLs in Javascript

2022-06-12 | Web | #Words: 735

It is a little troublesome to get URL parameters with JS, because JS can only get a certain part of the URL, but it cannot be subdivided. If you want to get a certain parameter, you also need to use string interception. So it’s divided into two steps:

  1. Get the parameter part of the URL
  2. Intercept a certain parameter (even broken down to parameter name and parameter value)

First assume that the URL is https://www.example.com/?keyword=abc&id=12.

JS gets the parameter part of the URL

First you need to use new URL() to create a URL object, and then use .search to get the URL parameter part.

code show as below:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Test</title>
</head>
<body>

<script>
let url=new URL('https://www.example.com/?keyword=abc&id=12'); /* Create a URL object */
let para = url.search; /* Get the URL parameter part */
document.write(para); /* Display the content of a on the screen */
</script>

</body>
</html>

Displayed as follows:

“?keyword=abc&id=12”

If you want to know more about URLs in Javascript, you can check out this article, which I think is pretty good: https://javascript.info/url

Ok, the next step is to intercept each part.

Intercept URL parameters

Multiple URL parameters are separated by the & symbol, so you can use JS’s split() to separate them. split() will put the separated contents into an array. But before using split(), you need to remove the question mark ? at the beginning of the parameter part, otherwise the first separated one will have this question mark ?. Use .substring(1) to ignore the first character & at the beginning.

code show as below:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Test</title>
</head>
<body>

<script>
url=new URL('https://www.example.com/?keyword=abc&id=12');
para = url.search; /* Get attributes (segment after "?") */
para=para.substring(1);
a=para.split("&");
/* Display the first and second parameters in separate lines */
document.write(a[0]);
document.write('<br>');
document.write(a[1]);
</script>

</body>
</html>

Displayed as follows:

"keyword=abc" and "id=12"

At this time, you can go one step further to obtain a certain parameter name or value. The code is as follows:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Test</title>
</head>
<body>

<script>
url=new URL('https://www.example.com/?keyword=abc&id=12');
para = url.search; /* Get attributes (segment after "?") */
para=para.substring(1);
a=para.split("&");
document.write(a[0].split("=")[0]); /* Parameter name of the first parameter */
document.write('<br>');
document.write(a[0].split("=")[1]); /* Parameter name of the first parameter */
</script>

</body>
</html>

Displayed as follows:

"keyword""abc"

​I hope these will help someone in need~