The JavaScript String
object has a built-in method called link()
that you can use to display a string
type data as a hypertext.
You need to pass the web address you want to be added to the href
attribute as the argument to the link()
method.
The following code example will transform the text "Go to Google"
as an anchor element <a>
to navigate toward "https://google.com"
:
const str = "Go to Google";
const url = str.link("https://google.com");
console.log(url); // <a href="https://google.com">Go to Google</a>
The implementation of the link()
method varies between different browsers, but I’ve tested the method on the latest Chrome and Safari version. The method also works in the NodeJS environment, so you can use it there as well. Just be sure to test the result first before you use the method.