I have a problem to get encoding the caret ^ symbol in the URL. The console log error messages are URIError: URI malformed. I am using the encodeURIComponent function to encode the data in the URL. After I use history.push the pathname. Below is my sample code:
companyName value is Test Character )(*&(^&%^%$#@)(
code value is Test Character Branch !@#$@%^&
const selectRow = async (code, companyName, e) => {
const encodedCompanyName = encodeURIComponent(companyName);
const encodedCode = encodeURIComponent(code);
console.log("encodedCompanyName:" + encodedCompanyName + "encodedCode:" +encodedCode );
e.preventDefault();
history.push({
pathname: `/branch-management/edit-branch/?companyName=${encodedCompanyName}&branchName=${encodedCode}`,
});
};
So the console.log results are:
encodedCompanyName:Test%20Character%20)(*%26(%5E%26%25%5E%25%24%23%40)(encodedCode:Test%20Character%20Branch%20!%40%23%24%40%25%5E%26
So when I want to get Parameter and URL, the URL's parameters encode values not the same as the above console log value. Below are my get parameter functions.
export const getParameterByName = (name, url = window.location.href) => {
name = name.replace(/[\]]/g, "\\$&");
console.log("URL:" + url);
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return "";
return decodeURIComponent(results[2].replace(/\+/g, " "));
};
Above console log URL values are: URL:http://localhost:3005/branch-management/edit-branch/?companyName=Test%20Character%20)(*%26(^%26%^%24%23%40)(&branchName=Test%20Character%20Branch%20!%40%23%24%40%^%26
I have checked the above URL values are not the same as what I encode code and companyName.
I want the expected results are http://localhost:3005/branch-management/edit-branch/?companyName=Test%20Character%20)(*%26(%5E%26%25%5E%25%24%23%40)(&branchName=Test%20Character%20Branch%20!%40%23%24%40%25%5E%26
Comparison:
Wrong URL in console log:
http://localhost:3005/branch-management/edit-branch/?companyName=Test%20Character%20)(*%26(^%26%^%24%23%40)(&branchName=Test%20Character%20Branch%20!%40%23%24%40%^%26
Wrong URL in browser:
http://localhost:3005/branch-management/edit-branch/?companyName=Test%20Character%20)(*%26(^%26%^%%24%23%40)(&branchName=Test%20Character%20Branch%20!%40%23%24%40%^%26
Expected correct URL:
http://localhost:3005/branch-management/edit-branch/?companyName=Test%20Character%20)(*%26(%5E%26%25%5E%25%24%23%40)(&branchName=Test%20Character%20Branch%20!%40%23%24%40%25%5E%26
Hope someone can guide me on how to solve this problem or can give me sample make it caret ^ can decode well. Thanks.