Encode URL in JavaScript?
Check out the built-in function encodeURIComponent(str) and encodeURI(str).
In your case, this should work:
var myOtherUrl =
"http://example.com/index.html?url=" + encodeURIComponent(myUrl);
encoding url in javascript not encoding &
Does not encode characters that have special meaning (reserved
characters) for a URI. The following example shows all the parts that
a URI "scheme" can possibly contain.
Reference
encodeURI
will not encode following special charcaters
A-Z a-z 0-9 ; , / ? : @ & = + $ - _ . ! ~ * ' ( ) #
let uri = "?qry=M & L"
console.log(encodeURI(uri))
How do I URL encode spaces and the word and ?
There are two ways of accomplishing this.
1. Use replace()
The first solution is to use the replace()
function, available on the string
primitive.
Instead of breaking up and joining the strings together with a different character again, you can use the simpler replace()
function.
Also, this function works in Internet Explorer 5.5 and above, which means it fulfils the requirements!
To use it, simply use the code below.
var word = "Windows and Mac";
word = word.replace(/\s/g, "%20");
word = word.replace(/and/ig, "%26");
console.log(word);
how to get page url without decode in javascript?
Just to make a clear and concise answer I will sum up all the comments.
For your problem the best solution is to use document[x].url
where x is the index of the URL part that you want to use.
The main difference for your problem between window.location.href
and document.url
is that the last one gives you the URL in a string format, whilest the other return the URL already parsed.
Using either one is completely normal and safe and is widely adopted in all modern browsers.
var url1 = document.URL;
var url2 = window.location.href;
document.getElementById("documentUrl").append (url1);
document.getElementById("windowLocationUrl").append (url2);
<div id="documentUrl">document.url: </div>
<div id="windowLocationUrl">window.location.href: </div>
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"));
javascript: How to URL encode strings that contain dashes (-)?
-
is a character that appears in the ASCII character set and has no special meaning in URLs. While you can encode it as %2D
, doing so is not needed nor is it normal. Encoding it would be like using %61
instead of a
.
There is no standard encoding function that will encode a -
character. replace
is the logical choice if you really, really want to.
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/
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
How to Merge Two Arrays in JavaScript and De-Duplicate Items
Http Get Request in JavaScript
Difference Between == and === in JavaScript
Deleting Array Elements in JavaScript - Delete VS Splice
Chrome Extension Message Passing: Response Not Sent
Combination of Async Function + Await + Settimeout
Regular Expression to Match Non-Ascii Characters
Convert Js Object to Json String
Best Way to Manage Chat Channels in Firebase
JavaScript Post Request Like a Form Submit
Get Difference Between 2 Dates in JavaScript
Calculate Text Width With JavaScript
JavaScript Equivalent of Python'S Zip Function
Negative Lookbehind Equivalent in JavaScript
How to Get the Current Date in JavaScript