Usefull JS code snippets
Just some small but sometimes usefull Javascript code snippets:
Add string that sorunds all regular expression matches:
var string = 'This is “text in quotes” and another “text in quotes”!';
string = string.replace(new RegExp(/“(.*?)”/, 'g'),'...$&...');
// This is ...“text in quotes”... and another ...“text in quotes”...!
Get different parts of the current URL:
window.location.hash: "#2"
window.location.host: "localhost:4200"
window.location.hostname: "localhost"
window.location.href: "http://localhost:4200/landing?query=1#2"
window.location.origin: "http://localhost:4200"
window.location.pathname: "/landing"
window.location.port: "4200"
window.location.protocol: "http:"
window.location.search: "?query=1"
Convert sick date formats like "Thu Aug 05 2021 15:33:32 GMT+0300 (Eastern European Summer Time)"
let date = new Date(event).toISOString().split('T')[0];
In case if you need to preserve the same date (like when you get it from a datepicker):
var datepickerDate = new Date(event)
var isoDateInCurrentZone = new Date(datepickerDate.getTime() - (datepickerDate.getTimezoneOffset() * 60000)).toISOString();
Execute some code before navigating to another page:
window.addEventListener('beforeunload', (event) => {
$('#loader').show();
});
Debug with date:
console.log(new Date().toISOString(), 'Log JS date in one liner')
Base64 encode and decode string with quotes:
// Encode:
window.btoa(unescape(encodeURIComponent('Text with "quotes"')))
// Decode:
decodeURIComponent(atob('VGV4dCB3aXRoICJxdW90ZXMi'))