JavaScript URL Decode function
I've used encodeURIComponent() and decodeURIComponent() too.
Why can't decodeURIComponent or decodeURI decode hello+world to hello world in JavaScript?
The behavior of decideURIComponent
is defined as "inverse" operation of encodeURIComponent
:
The
decodeURIComponent
function computes a new version of aURI
in which each escape sequence and UTF-8 encoding of the sort that might be introduced by theencodeURIComponent
function is replaced with the character that it represents.
And encodeURIComponent
does not replace spaces with +
, but with %20
.
(similar for decodeURI
)
If "+" is valid, surely, there has to be a built-in function in JavaScript that can convert "hello+world" to "hello world"?
Of course there is:
"hello+world".replace(/\+/g, ' ');
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'));
Unable to decode/encode Url properly
Some of your strings in filterDecode
have special meaning as regular expressions. When converting the string to a regular expression, you need to wrap each character in []
so it will be matched literally.
You don't need to concatenate /
when creating regexDe
.
There's no need for the for(b...)
loops. Use the regular expression in the replace()
call and it will perform all the replacements at once, since it has the g
flag.
Put the encode strings that contain %
at the beginning of the array. Otherwise, when you encode something like =
as %3D
, a later iteration of the outer loop will re-encode that as %253D
. You only want to encode this if it was in the original string, not an intermediate step.
var Url = {
filterDecode: ["%252F", "%253A", "%253D", "%253F", "%252B", "%2B", "%3A", "%3D", "%3F", "%2F", "%26"],
filterEncode: ["%2F", "%3A", "%3D", "%3F", "%2B", "+", ":", "=", "?", "/", "&"],
strToRe: function(str) {
let reStr = str.split("").map(c => '[' + c + ']').join('');
return new RegExp(reStr, "g");
},
decode: function(decodeText) {
let a;
let filterEncode = Url.filterEncode;
let filterDecode = Url.filterDecode;
for (a = 0; a < filterDecode.length; a++) {
decodeText = decodeText.replace(Url.strToRe(filterDecode[a]), filterEncode[a]);
}
return decodeText;
},
encode: function(encodeText) {
let a, b;
let filterEncode = Url.filterEncode;
let filterDecode = Url.filterDecode;
for (a = 0; a < filterEncode.length; a++) {
encodeText = encodeText.replace(Url.strToRe(filterEncode[a]), filterDecode[a]);
}
return encodeText;
}
}
console.log(Url.encode("="));
console.log(Url.decode("%3D"));
console.log(Url.encode("%3F"));
console.log(Url.decode("%253F"));
console.log(Url.encode("%3F ="));
console.log(Url.decode("%253F %3D"));
How to decode url-encoded string in javascript
That is not UTF-8, that is percent encoding also known as url encoding.
You can use decodeURIComponent() to convert it back before displaying it
$("#quote1 span").html(decodeURIComponent(text1));
why javascript protocol decode the URL automatically?
Because it's in an href
attribute, where URLs are expected, so the browser is "normalizing" the URI-encoding of the "URL" (which is using the javascript
pseudo-scheme).
You can put it in a different attribute and then get that, like so:
function myFunction(element) { console.log(element.getAttribute("data-value")); //it will generate =cDO4w67epn64o76}
<a href="javascript:;" onclick="myFunction(this)" data-value="%3DcDO4w67epn64o76">press</a>
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,
})
}
Related Topics
Uncaught Typeerror: Illegal Invocation in JavaScript
Alternative to a Million If Statements
How to Replace Remapcolums with Remapcolumnsbyname in Free Jqgrid
How to Create a Dialog with "Ok" and "Cancel" Options
Differencebetween String.Slice and String.Substring
Differencebetween Substr and Substring
Nodevalue VS Innerhtml and Textcontent. How to Choose
Moment Js Date Time Comparison
How to Find the Height of Text on an HTML Canvas
Getting the Return Value of JavaScript Code in Selenium
What Does [Object Object] Mean? (Javascript)
How to Use Ajax to Do File Upload
Clone Object Without Reference JavaScript
Wrong React Hooks Behaviour with Event Listener
Force Download Through Js or Query