How to Convert URL to String in JavaScript

To convert a URL to a String in JavaScript, you can use either the toString()” or encodeURI()” methods.

Method 1: Using the toSting() function

The toString() is a built-in JavaScript method “used to convert the whole URL to a string.” The URL.toString() is a stringifier method that returns a USVString containing the whole URL.

Even the query string has been converted to a string. So we can’t store query string key values in objects or variables. To store the query string, we need to convert them into objects.

Syntax

url.toString();

Return Type

String – It will return a string.

Example

const url = new URL("https://google.com");
console.log(typeof (url));
let urlString = url.toString();
console.log(urlString);
console.log(typeof (urlString));

Output

object
https://google.com/
string

In the above example, we create one url instance, then convert them into a string using the toString() method. To check the data type in JavaScript, use the typeof() function.

Method 2: Using the encodeURI() function

The encodeURI() is a built-in JavaScript function that encodes a URI by replacing each instance of certain characters with one, two, three, or four escape sequences representing the UTF-8 encoding of the character. It replaces each character with an escape sequence representing a UTF-8 character.

Syntax

encodeURI(URI);

Parameters

URI – The encodeURI() function takes a UR in this method.

Return value

String: It will return a string value based on URI.

Example 1

const url = new URL("https://google.com");
console.log(typeof (url));
let urlString = encodeURI(url);
console.log(urlString);
console.log(typeof (urlString));

Output

object
https://google.com/
string

Example 2

Let’s take an example of URI with query strings.

const url = new URL("http://google.com/person?name=tony&age=31&proffession=coder");
console.log(typeof (url));
let urlString = encodeURI(url);
console.log(urlString);
console.log(typeof (urlString));

Output

object
http://google.com/person?name=tony&age=31&proffession=coder
string

That’s it.

Leave a Comment