Home > Software design >  decode Cyrillic for insertion into a link
decode Cyrillic for insertion into a link

Time:06-21

I want to make a form where there will be a line with a search, which will immediately search for a track on Spotify.

<form name="search">
  <input id="inputSearch" type="text" name="search" placeholder="enter track">
  <button id="btnSearch" type="button" onclick="window.open('https://open.spotify.com/search/' escape(document.forms['search'].elements['search'].value), '_blank')">search</button>
</form>

Here is an example https://jsfiddle.net/z7po2vwg/

Now everything works, except for the search in Cyrillic, that is, if you insert something like фывфыв, then it will be encoded in the link. and look like this %u0444%u044B%u0432%u0444%u044B%u0432

I tried using decodeURIComponent to remove encoding

window.open('https://open.spotify.com/search/' decodeURIComponent(escape(document.forms['search'].elements['search'].value)), '_blank')

But I am getting an error

Uncaught URIError: URI malformed at decodeURIComponent () at HTMLInputElement.

What can be done in this case?

CodePudding user response:

MDN docs for escape:

Warning: Although escape() is not strictly deprecated (as in "removed from the Web standards"), it is defined in Annex B of the ECMA-262 standard, whose introduction states:

… All of the language features and behaviors specified in this annex have one or more undesirable characteristics and in the absence of legacy usage would be removed from this specification. … … Programmers should not use or assume the existence of these features and behaviors when writing new ECMAScript code. …

escape doesn't have a use case in modern JavaScript code, and the bug you're seeing here is one of the "undesirable characteristics" mentioned.

Instead, you can use encodeURIComponent:

window.open('https://open.spotify.com/search/'
      encodeURIComponent(document.forms.search.elements.search.value)), '_blank')
  • Related