I have search textbox. When the user enters some text my querystring shows the text with ASCII characters like %20 and %3F. I want to show this text in one of my textboxes without any ASCII codes like normal HTML text. How can I do this in Javascript?
-
3That's normal URL-encoding, it's required for any special characters in a URL query string. The server will automatically decode it.Barmar– Barmar2014-06-13 13:04:29 +00:00Commented Jun 13, 2014 at 13:04
-
1I am showing of that value in textbox which is encoded. I need to decode it in the textbox.Suresh Ponnukalai– Suresh Ponnukalai2014-06-13 13:05:49 +00:00Commented Jun 13, 2014 at 13:05
Add a comment
|
2 Answers
Use decodeURIComponent():
var querystring = "?foo=bar%20baz";
console.log(decodeURIComponent(querystring));
Comments
You can also use URLSearchParams along with decodeURIComponent.
Personally I prefer URLSearchParams.
From my testing, decodeURIComponent literally just strips/replaces the URI encodes, but URLSearchParams only returns the values of specific querystrings and allows methods to get specific key/value pairs like below.
Example:
var querystring = "?foo=bar%20baz";
var decoded = decodeURIComponent(querystring)
console.log('decoded:');
console.log(decoded)
var urlParams = new URLSearchParams(querystring);
var foo = urlParams.get('foo');
console.log('foo:');
console.log(foo)
1 Comment
Rory McCrossan
This is the better approach now that
URLSearchParams has widespread support. I don't think it was even proposed when the question was originally asked :)