0

How do I encode string for URI, for example Capitan's Hat -> Capitan%27s+Hat or Сhristmas Hat -> %D0%A1hristmas+Hat

I tried, several methods encodeURIComponent(), encodeURI(), but nothing brings close enough to what I need. Any idea how it is being encoded?

Escape() does bring relatively close result for capitan's hat, but then completely off for christmas hat.

EDIT:

As Thomas said, encodeURIComponent does the job, but how achieve replacing encoded characters, back to characters? As in example Сhristmas Hat -> "%D0%A1hristmas+Night"

I know replace(), targeting each character would work, but is there more universal option?

qwerty
  • 51
  • 7
  • For which part of the URI? For usage in the query string, `encodeURIComponent` is doing the right thing. – Thomas Jun 07 '22 at 17:54
  • Seems you are right, encodeURIComponent does the right job. But how do I replace all encoded characters, back to characters? But only characters, as in example ```Сhristmas Hat -> "%D0%A1hristmas+Night" ``` I know replace(), targeting each character would work, but is there any universal option? – qwerty Jun 07 '22 at 18:20
  • `decodeURIComponent(encodeURIComponent('Capitan\'s Hat'))` – Jared Farrish Jun 07 '22 at 19:20

1 Answers1

0

const encode = str => new URLSearchParams([['', str]]).toString().slice(1)
const decode = str => new URLSearchParams('=' + str).get('')

console.log(encode('Сhristmas Hat'))
console.log(decode('%D0%A1hristmas+Hat'))

Explanation: the URLSearchParams constructor can take either an array of key/value pairs ([['key', 'value']]) or a query string ('key=value'). Calling get on a URLSearchParams instance retrieves the unencoded value of that key; meanwhile, calling toString gives the full string of URL-encoded key/value pairs. In this case, we use empty string '' as the key, because the key isn't important.

The algorithm for URL encoding query parameters is similar to that of encodeURIComponent, but it also replaces spaces with +.

Lionel Rowe
  • 5,164
  • 1
  • 14
  • 27