I am trying to encode all parameters before appending them to a web URL. The encoding works correctly for most parameters, but when the video title is in Japanese, it gets encoded twice. However, this issue does not occur with English characters.
const generateVideoURL = async (
vPath: string,
videoTitle: string,
completedId: string,
startedAt: string,
endedAt: string,
testUrl: string
) => {
const maxUrlLength = 2000;
const estimatedOtherLength = 300;
const maxTitleLength = maxUrlLength - estimatedOtherLength;
let truncatedTitle = videoTitle;
if (truncatedTitle.length > maxTitleLength / 3) {
truncatedTitle =
truncatedTitle.substring(0, maxTitleLength / 3) + '...';
}
let encodedTitle = encodeURIComponent(truncatedTitle);
const queryParams = new URLSearchParams({
vPath,
vtitle: encodedTitle,
cid: encodeURIComponent(completedId),
start: encodeURIComponent(startedAt),
end: encodeURIComponent(endedAt),
});
if (route.query.continue === 'retest') {
queryParams.append('continue', 'retest');
}
let finalURL = `${testUrl}?${queryParams.toString()}`;
};
I am trying to encode all parameters before appending them to a web URL. The encoding works correctly for most parameters, but when the video title is in Japanese, it gets encoded twice. However, this issue does not occur with English characters.
const generateVideoURL = async (
vPath: string,
videoTitle: string,
completedId: string,
startedAt: string,
endedAt: string,
testUrl: string
) => {
const maxUrlLength = 2000;
const estimatedOtherLength = 300;
const maxTitleLength = maxUrlLength - estimatedOtherLength;
let truncatedTitle = videoTitle;
if (truncatedTitle.length > maxTitleLength / 3) {
truncatedTitle =
truncatedTitle.substring(0, maxTitleLength / 3) + '...';
}
let encodedTitle = encodeURIComponent(truncatedTitle);
const queryParams = new URLSearchParams({
vPath,
vtitle: encodedTitle,
cid: encodeURIComponent(completedId),
start: encodeURIComponent(startedAt),
end: encodeURIComponent(endedAt),
});
if (route.query.continue === 'retest') {
queryParams.append('continue', 'retest');
}
let finalURL = `${testUrl}?${queryParams.toString()}`;
};
Share
Improve this question
asked Feb 4 at 5:29
Bimal KafleBimal Kafle
275 bronze badges
1 Answer
Reset to default 4Indeed, URLSearchParams#toString()
will percent encode all the characters in the application/x-www-form-urlencoded percent-encode set,1 so you should not encode these yourself.
1. Along with encoding space characters as +
.