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?

3
  • For which part of the URI? For usage in the query string, encodeURIComponent is doing the right thing. Commented Jun 7, 2022 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? Commented Jun 7, 2022 at 18:20
  • decodeURIComponent(encodeURIComponent('Capitan\'s Hat')) Commented Jun 7, 2022 at 19:20

1 Answer 1

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 +.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.