• Node.js Video Tutorials

NodeJS - url.search property



The NodeJS url.search property of URL class gets and sets the serialized query portion of the URL. Invalid URL characters will be percent-encoded if they appear in the value assigned to the username property. The selection of characters to percent-encode may differ slightly from what the url.parse() and url.format() methods would produce.

There are several utilities for URL resolution and parsing provided by the Node.js URL module and search property is one in that.

Syntax

Following is the syntax of the NodeJS search property of URL class

URL.search

Parameters

This property does not accept any parameters.

Return Value

This property sets and gets the query portion of the URL.

Example

If we assign a URL to the NodeJS url.search property, it will get the query portion from the give URL.

In the following example, we are trying to get the query segment from the input URL.

const http = require('url');

const myURL = new URL('https://www.tutorialspoint.com/?Node.js-articles');
console.log("The URL: " + myURL.href);
console.log("Query portion of the URL is: " + myURL.search);

Output

After executing the above program, the search property gets the query segment from the input URL.

The URL: https://www.tutorialspoint.com/?Node.js-articles
Query portion of the URL is: ?Node.js-articles

Example

We can set any valid value to the query portion of the provided URL.

In the program below, we are trying to set a value to the query portion of the input URL.

const http = require('url');

const myURL = new URL('https://www.tutorialspoint.com/?Node.js-articles');
console.log("The URL: " + myURL.href);
console.log("Query portion of the URL is: " + myURL.search);

myURL.search = "JavaScript-Articles";
console.log("Modifying the query portion to- " + myURL.search);
console.log("After modifying: " + myURL.href);

Output

As we can see in the output below, the query segment of the URL is modified.

The URL: https://www.tutorialspoint.com/?Node.js-articles
Query portion of the URL is: ?Node.js-articles

Modifying the query portion to- ?JavaScript-Articles
After modifying: https://www.tutorialspoint.com/?JavaScript-Articles

Example

If any invalid URL characters are included in the query portion of the URL, those characters will be percent-encoded.

In the following example, we are assigning an URL with invalid characters in username portion.

const http = require('url');

const myURL = new URL('https://www.tutorialspoint.com/?你好-Articles');

console.log("The URL: " + myURL.href);
console.log("Value in query portion: " + myURL.search);

Output

As we can see in the output, the invalid characters in the URL got percent-encoded.

The URL: https://www.tutorialspoint.com/?%E4%BD%A0%E5%A5%BD-Articles
Value in query portion: ?%E4%BD%A0%E5%A5%BD-Articles
nodejs_url_module.htm
Advertisements