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:
First assume that the URL is https://www.example.com/?keyword=abc&id=12
.
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:
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.
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:
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:
I hope these will help someone in need~