🏠 back to Observable

String.prototype.link() is deprecated; is there a recommended alternative?

Mozilla tells us that String.prototype.link() is deprecated. I found this to be a handy way to link array objects to create URLs in tables.

I haven’t found a similarly easy and short alternative. Any suggestions?

You could write a custom function:

link = (text, href) => {
  const link = DOM.element('a', { href })
  link.textContent = text
  return link
}
1 Like

Beautiful, Jed! Very short and perfectly clear. Thank you!

1 Like

Another version with optional escaping:

function link(text, href, escape = true) {
  return html`<a href="${href}">${escape ? DOM.text(text) : text}`;
}

Escaping is a good idea if you don’t have complete control over the text (i.e. you have neither authored nor vetted it). Disabling it will allow you to use formatting or even other HTML elements/nodes inside the text.

2 Likes

Nice addition, @mootari! Just to clarify — my initial version escapes the HTML.

1 Like

Of course, I should have emphasized “optional”! :blush:

Edit: Btw, I found that in the above example I didn’t need to escape the attribute value. All my attempts at breaking the resulting markup failed. I’m not quite sure yet why that is though.

1 Like

Turns out I didn’t test properly. Attribute values do need to get escaped:

1 Like