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 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.

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, and then convert it into a string using the toString() method.

Method 2: Using the encodeURI() function

The encodeURI() method is used to encode 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.

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

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.