Home >Web Front-end >JS Tutorial >How Can I Retrieve Values from URL Parameters in JavaScript?

How Can I Retrieve Values from URL Parameters in JavaScript?

Linda Hamilton
Linda HamiltonOriginal
2024-12-24 16:54:28726browse

How Can I Retrieve Values from URL Parameters in JavaScript?

Retrieving Values from URL Parameters in JavaScript

When dealing with URLs that contain query string parameters (like www.test.com/t.html?a=1&b=3&c=m2-m3-m4-m5), accessing and manipulating these parameters is often necessary. However, JavaScript doesn't inherently provide built-in capabilities for handling query strings.

To overcome this, browsers and Node.js leverage the URL object to parse and work with these parameters. By creating a URL instance from the given URL string, you can access individual parameters using the searchParams property.

var url_string = "http://www.example.com/t.html?a=1&b=3&c=m2-m3-m4-m5"; 
var url = new URL(url_string);
var c = url.searchParams.get("c");

The get() method of searchParams takes the parameter name ("c" in this example) and returns its associated value. This allows you to retrieve the entire value of parameter c, even if it contains multiple segments like in the provided example.

The above is the detailed content of How Can I Retrieve Values from URL Parameters in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn