Decoding Url Parameters with JavaScript

Decoding URL parameters with JavaScript

Yes it is true that decodeURIComponent function doesn't convert + to space. So you have to replace the + using replace function.

Ideally the below solution works.

var str_name = 'This+is+a+message+with+spaces';
decodeURIComponent((str_name + '').replace(/\+/g, '%20'));

Decoding url within encoded parameters (returnUrl)

You need decodeURIComponent().

I've deleted a space before site in the URL:

const url1 = new URL('https://force.com?positionId=a0w0X000007HjBuQAK&lang=fr&mediaChannel=a0o0X00000EGQ5TQAX&returnUrl=https%253A%2F%2force.com%2Fcxsrec__cxsSearchDetail%3Fid%3Da0w0X000007HjBuQAK%26lang%3Dfr%26mediaChannel%3Da0o0X00000EGQ5TQAX%26returnUrl%3Dhttps%253A%2F%2force.com%2Fcxsrec__cxsSearch%253Flang%253Dfr%2526mediaChannel%253Da0o0X00000EGQ5TQA%2526site%253DFrance%2526hcFilter%253Da0Z0X00000XiFF3UAN%252Ca0Z0X00000XiUqTUAV%2526orderBy%253DPosition_name__c%2526orderDir%253Dasc%2526mediaChannel%253Da0o0X00000EGQ5TQAX%26lang%3Dfr%26mediaChannel%3Da0o0X00000EGQ5TQAX');
const params1 = new URLSearchParams(url1.search);
const returnUrl = params1.get('returnUrl');

const url2 = new URL(decodeURIComponent(returnUrl));
const params2 = new URLSearchParams(url2.search);
const site = params2.get('site');

console.log(site);

See some details in encodeURIComponent() description

How to encode URL parameters?

With PHP

echo urlencode("http://www.image.com/?username=unknown&password=unknown");

Result

http%3A%2F%2Fwww.image.com%2F%3Fusername%3Dunknown%26password%3Dunknown

With Javascript:

var myUrl = "http://www.image.com/?username=unknown&password=unknown";
var encodedURL= "http://www.foobar.com/foo?imageurl=" + encodeURIComponent(myUrl);

DEMO: http://jsfiddle.net/Lpv53/

Decode parameters encoded using the JS encodeURIComponent function

The URL wasn't encoded correctly to begin with. previewImage.ashx?id=1&text=Fran%25E7ois%2520%2B%2520Anna is not the correct URL encoding of François + Anna

I believe the correct encoding should have been previewImage.ashx?id=1&text=Fran%E7ois+%2B+Anna or previewImage.ashx?id=1&text=Fran%E7ois%20%2B%20Anna

Once the encoding has been fixed, then you should be able to retrieve the result via a simple Context.Request.QueryString["text"] call. No need to do anything special.

How to encode and parse / decode a nested query string Javascript

So, the qs library proved to be my savior after all. I just wasn't implementing it correctly before. So, with the same form data structure, just make sure to import qs to your form component file:

import qs from 'qs'

and then make your encode function nice and succinct with:

     // Transforms the form data from the React Hook Form output to a format Netlify can read
const encode = (data) => {
return qs.stringify(data)
}

Next, use this encode function in your handle submit function for the form:

 // Handles the post process to Netlify so we can access their serverless functions
const handlePost = (formData, event) => {
event.preventDefault()

fetch(`/`, {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: encode({ "form-name": 'add-registration-form', ...formData }),
})
.then((response) => {
reset()
if(response.status === 200) {
alert("SUCCESS!")
} else {
alert("ERROR!")
}
console.log(response)
})
.catch((error) => {
console.log(error)
})
}

Finally, this is what your Netlify submission-created.js file should look like more or less:

const sanityClient = require("@sanity/client")
const client = sanityClient({
projectId: process.env.GATSBY_SANITY_PROJECT_ID,
dataset: process.env.GATSBY_SANITY_DATASET,
token: process.env.SANITY_FORM_SUBMIT_TOKEN,
useCDN: false,
})
const qs = require('qs')
const { nanoid } = require('nanoid');

exports.handler = async function (event, context, callback) {

// Pulling out the payload from the body
const { payload } = JSON.parse(event.body)

// Checking which form has been submitted
const isAddRegistrationForm = payload.data.formId === "add-registration-form"

// Build the document JSON and submit it to SANITY
if (isAddRegistrationForm) {
const parsedData = qs.parse(payload.data)

let schedule = parsedData.days
.map(d => (
{
_key: nanoid(),
_type: "classDayTime",
day: d.day,
time: {
_type: "timeRange",
start: d.start,
end: d.end
}
}
))

const addRegistrationForm = {
_type: "addRegistrationForm",
submitDate: new Date().toISOString(),
_studentId: parsedData._id,
classType: parsedData.classType,
schedule: schedule,
language: parsedData.language,
classSize: parsedData.size,
}
const result = await client.create(addRegistrationForm).catch((err) => console.log(err))
}

callback(null, {
statusCode: 200,
})
}

Split URL into params

If your URL is encoded (due to space character) you need to properly decode it.

const url = '?Point%20Cook-VIC-3030';
// Decode URL and remove initial '?'
const decodedUrl = decodeURIComponent(url).substring(1);
// Split parameters
const paramerters = decodedUrl.split('-');


Related Topics



Leave a reply



Submit