1

I have one one hidden paramter in form whose value is

custAddress=CustomerAddress.do?fisrtName=scott&lastName=Miles

I want to encode it before sending it and so that characters like & can be replaced with %26 etch

i tried using javascript built-in encodeURI("urlToencode") but does not encode characters like &?

2 Answers 2

4

Try this code line,

encodeURIComponent("fisrtName=scott&lastName=Miles");
Sign up to request clarification or add additional context in comments.

Comments

1

Use https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/encodeURIComponent

You need to call that on each dynamic part (name and value) of the URL query string. So the question is what is the URI component in custAddress=CustomerAddress.do?fisrtName=scott&lastName=Miles That doesn't really look like a URL because you have the = before the ?

The most sense that I can make is that the full URL is something like

http://myserver/file.do?custAddress=CustomerAddress.do?fisrtName=scott&lastName=Miles

In which case, you should build your URL like

var custAddress = "CustomerAddress.do?fisrtName=scott&lastName=Miles";
var initialPath= "/path/to/file.do?";
var url = initialPath + "custAddress=" + encodeURIComponent(custAddress);

Since you mentioned jQuery, you can use a $.param, looks cleaner and does the encoding for you, and you can give it multiple query parameters at once

var url  = initialPath + $.param({
    custAdrress: custAddress, 
    otherParam: "paramVal",
    // Both the param name and value need to be encoded and $.param does that for you
    "funny Name & Param": "funny & value ="
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.