Ganesh
Ganesh

Reputation: 53

How to pass special characters as query string in url

I am trying to pass special characters as querystring in url as part of GET request. I am constructiong that string in javascript function.

var queryString = "list=ABC-48+12&level=first";

Then I append the string to url as part of request which goes to struts action class. In the action class I get the "list" value as "ABC-48 12", the "+" character is not passed. How to pass special characters in the string as part of url and get back in the java class?

Please let me know.

Thanks.

Upvotes: 5

Views: 22931

Answers (2)

Ryder
Ryder

Reputation: 514

You need to use a regular expression with the global option set as the first parameter instead of a string: (in regular expressions "+" is a special character, so we have to escape it with a backslash.)

safeQueryString = safeQueryString.replace(/+/g, '%2B');

Upvotes: -3

Darin Dimitrov
Darin Dimitrov

Reputation: 1039368

You should url encode it using the encodeURIComponent function:

var queryString = 
    "list=" + encodeURIComponent("ABC-48+12") + 
    "&level=" + encodeURIComponent("first");

This function will take care of properly encoding your query string parameter values:

list=ABC-48%2B12&level=first 

Upvotes: 13

Related Questions