Reputation: 5483
Let's say I use the URL interface to create a new URL. E.g. like that:
new URL('https://www.example.com/démonstration.html?query=6#bla')
Now I need this as a plain string. How do I best convert it?
Note: The examples here are minimal examples. I obviously don't convert a (hardcoded) string to an URL object and back to a string. To give some context, imagine I modify the URL object in between (possibly with user input) and/or pass it to different functions or so. In the end, I have an URL object and want it as a plain string.
I've found the following ways:
via href
property:
(new URL('https://www.example.com/démonstration.html?query=6#bla')).href
// "https://www.example.com/d%C3%A9monstration.html?query=6#bla"
via toString
method:
(new URL('https://www.example.com/démonstration.html?query=6#bla')).toString()
// "https://www.example.com/d%C3%A9monstration.html?query=6#bla"
As you can see, in my example, it returns exactly the same.
So looking at the doc you notice:
href
is "a USVString containing the whole URL."toString
returns "a USVString containing the whole URL. It is a synonym for URL.href, though it can't be used to modify the value."Okay, I don't want to modify it. But are there really no differences? Maybe regarding performance, browser support¹ or even code style? I have to decide for one, so which one should I choose?
¹ Actually I can see there are differences in the compatibility table for these conversion ways. So I guess there are also some legacy implementations that handle things differently or so. I cannot believe these are true "synonym" and this gab in browser support seems to support that believe.
Upvotes: 14
Views: 2170
Reputation: 664195
According to the specification, they are doing exactly the same. The href
attribute is marked up as a stringifier
, which means that in JavaScript the class gets a toString
method with exactly the same behaviour as the attribute.
As you have noticed, browser support is not the same for them. Also one is more to type and transmit than the other. This comes down entirely to preference. However, personally I find that an explicit toString
call best conveys the message "I have an URL object and want it as a plain string."
Upvotes: 12