iansan5653/unraw

' does not translate to '

juxuanu opened this issue · 2 comments

Maybe I misunderstand the usage of this package.
I am trying to use the response of an API to set some dynamic strings displayed in a Next.js site.

For example, in the <Head> of the document:

<title>{buildPageTitle(currentVideo?.snippet.title)}</title>

with buildPageTitle being

function buildPageTitle(songTitle?: string): string {
  const pre = "Música";

  console.debug(songTitle);

  if (!songTitle) return pre;
  if (songTitle.length > 30)
    return [pre, " · ", songTitle.slice().slice(0, 29), "… "].join(" ");
  return [pre, songTitle].join("  ·  ");
}

And the console.debug call is printing Concert Buhos La Mercè &#39;17 - Concert Estrella Damm which should be Concert Buhos La Mercè '17 - Concert Estrella Damm.

I tried using unraw to wrap buildPageTitle, but I have seen no effect.

I have succesfully solved this issue with

function parseString(str: string): string | null {
  return new DOMParser().parseFromString(str, "text/html").documentElement
    .textContent;
}

But I wonder if this should be handled in this package?

Hi @juxuanu - this package is intended to be the opposite of JavaScript's built-in String.raw method. This means that it will unescape JavaScript-form escape sequences, but not HTML-form escape sequences. So it would decode the sequence \u0027 (27 is the base-16 form of 39), but not &#39; which is an HTML entity.

For example:

const rawTitle = String.raw`Concert Buhos La Mercè \u002717 - Concert Estrella Damm`

console.log(unraw(rawTitle))
// Logs: Concert Buhos La Mercè '17 - Concert Estrella Damm

For this, I think taking advantage of the DOMParser API as you have already done is the best approach.

As this is expected behavior, I'm going to go ahead and close this issue out. But I won't lock the thread - feel free to reply if you have any more questions.