Jenna Leaf
Jenna Leaf

Reputation: 2462

javascript : how to replace special symbols/characters that will break your query string in your URL

I have this components in my URL --

var myType="Air B&B";
var myID="RestInPeace";
var myURL="http://myhome.com?type="+myType+"&name="+myID;
alert(myURL);  //http://myhome.com?type=Air B&B&id=RestInPeace

The '&' inside myType has broken your query here:

http://myhome.com?type=Air B&B&id=RestInPeace

The page relies on the id to locate the record. It won't get it because the '&' inside the type has broke the query! Any uri sensitive characters inside myType needs to treated so it won't break the query.

Upvotes: 0

Views: 2375

Answers (3)

AmigoJack
AmigoJack

Reputation: 6119

Since version 1.5 (ECMA-262 3rd edition, December 1999) JavaScript supports the functions encodeURI() and encodeURIComponent() for exactly this job. I have no idea how you two guys could have overseen this.

See also the question Should I use encodeURI or encodeURIComponent for encoding URLs?

Upvotes: 1

Chandradeepta Laha
Chandradeepta Laha

Reputation: 386

The best way to do this is using URL(). Create a new URL using

var myURL = new URL('http://myhome.com');

Then append search parameters like

var myType="Air B&B";
var myID="RestInPeace";
myURL.searchParams.set('type',myType);
myURL.searchParams.set('name',myID);

This will return an object like

hash: ""
host: "myhome.com"
hostname: "myhome.com"
href: "http://myhome.com/?type=Air+B%26B&name=RestInPeace"
origin: "http://myhome.com"
password: ""
pathname: "/"
port: ""
protocol: "http:"
search: "?type=Air+B%26B&name=RestInPeace"
searchParams: URLSearchParams {}
username: ""

So basically it will preserve your query automatically

Upvotes: 1

Jenna Leaf
Jenna Leaf

Reputation: 2462

Since the second param is not the key to load the record, I will sacrifice the '&' in the type param.

These characters will break your query in your URI : $ & : ' " < > [ ] + { }. See below the quick replace by escaping those symbols inside [] : meaning any ONE of those symbols inside []

var myType="Air B&B";
var myID="RestInPeace";
var myURL="http://myhome.com?type="+myType.replace(/[\$\&\'\"\:\<\>\[\]\{\}\+]/g, '^')+"&name="+myID;
alert(myURL);  //http://myhome.com?type=Air B^B&name=RestInPeace

Now the '&' inside myType is replaced. And the query is preserved.

http://myhome.com?type=Air B^B&name=RestInPeace

Upvotes: -1

Related Questions