Ahmad
Ahmad

Reputation: 887

Escape # symbol in serialized string

I have a serialized string which I am sending to server something like below:

counter=1&Id=4&type=2332&amount=3232&gstIncluded=3232&paymentMethod=2&notes=2332#fdsf&docId=0&ref=3232&isEdit=true

The problem which I am facing here is that there is "#" symbol in notes added by user. This results in breaking of the query string and I don't receive data after # in controller. Even docId, ref and isEdit are skip.

Can anyone please tell the better solution for this.

I have tried html escape the notes field but it don't escapes #.

Upvotes: 1

Views: 43

Answers (3)

Jack Bashford
Jack Bashford

Reputation: 44125

# is a character that you'd need to encode when it's in a URI (Uniform Resource Identifier), because it's normally used to show which ID has been selected/directed to.

You may see a # at the end of the URI in the address bar, and it may be followed by the ID of an element on the page - an example is the Lodash docs (_.uniqBy for example. You can use the inbuilt encodeURIComponent function to encode it. Encoded, it looks like %23:

console.log(encodeURIComponent("#"));

You can also encode the full URI in this way:

console.log(encodeURIComponent("counter=1&Id=4&type=2332&amount=3232&gstIncluded=3232&paymentMethod=2&notes=2332#fdsf&docId=0&ref=3232&isEdit=true"));

Upvotes: 1

arpit sharma
arpit sharma

Reputation: 405

Try this

let url = "counter=1&Id=4&type=2332&amount=3232&gstIncluded=3232&paymentMethod=2&notes=2332#fdsf&docId=0&ref=3232&isEdit=true";
url.replace("#","%23");

Then send it to the server will take the ascii value of reserve character

Upvotes: 0

Gabriel Cousin
Gabriel Cousin

Reputation: 11

You can use encodeURIComponent on notes value (and only on this specific value, otherwise you won't be able to parse other params) - it will escape the hashtag. See docs on MDN: https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/encodeURIComponent

Upvotes: 1

Related Questions