Skip to content

Instantly share code, notes, and snippets.

@masautt
masautt / 7bbszl.js
Created September 6, 2019 03:39
How to find longest substring without repeating characters in JavaScript?
const lengthOfLongestSubstring = s => {
let longest = 0;
let start = 0;
const seen = {};
[...s].forEach((char, i) => {
if (char in seen && start <= seen[char]) {
longest = Math.max(i - start, longest);
start = seen[char] + 1;
}
@masautt
masautt / n679h6.js
Created September 4, 2019 17:28
How to replace all occurrences of a string in JavaScript?
// Using RegEx
String.prototype.replaceAll = function(search, replacement) {
var target = this;
return target.replace(new RegExp(search, 'g'), replacement);
};
// Split and Join (Functional Implementation)
String.prototype.replaceAll = function(search, replacement) {
@masautt
masautt / r460xpv.js
Created September 3, 2019 23:26
How to remove an element from an array in JavaScript?
let arr = [1, 2, 3, 4, 5];
// Remove from the front
arr.pop();
console.log(arr); // --> [2, 3, 4, 5];
// Remove from back
arr.unshift( );
@masautt
masautt / h0fs1xb.js
Created September 3, 2019 23:22
How to redirect to another webpage in JavaScript?
// Through the console?
window.location.replace("https://google.com");
// Put it on a button?
document.getElementById("myBtn").addEventListener("click", () => {
window.location.href = "https://google.com";
});
@masautt
masautt / r460xpv.js
Created September 3, 2019 23:19
How to check if a string contains a substring in JavaScript?
let str = "Masautt";
let subString = "sau";
console.log(str.includes(subString)); // true
@masautt
masautt / e37uqws.html
Last active September 12, 2019 05:26
How to create hyperlink in HTML?
<a href="https://google.com" target="_blank">GO TO GOOGLE.COM IN SEPARATE WINDOW</a>
@masautt
masautt / y80wde7.js
Created September 3, 2019 23:06
How to randomly generate alpha-numeric id in JavaScript?
let idLength = 6;
Math.random().toString(36).slice(idLength); // y80wde7
@masautt
masautt / wioawyg.js
Last active September 3, 2019 22:58
How to sort array of objects by value in JavaScript?
let arr = [
{ prop: "7" },
{ prop: "3" },
{ prop: "6" },
{ prop: "1" }
]
//Sort in ascending
arr.sort(function(a, b) {
return (a.prop - b.prop);
@masautt
masautt / hieewlp.js
Last active September 3, 2019 22:59
How to sort array in JavaScript?
var arr = ["7", "2", "5", "9"];
// Sort in ascending order?
arr.sort(); // --> 2,5,7,9
// Descending order?
arr.reverse(); // --> 9,7,5,2
@masautt
masautt / 10n1myo.js
Last active September 3, 2019 22:59
How to check for empty Object in JavaScript?
//ES 7+
Object.entries(obj).length === 0 && obj.constructor === Object
//ES 5+
Object.keys(obj).length === 0 && obj.constructor === Object
//ES 5-
function isEmpty(obj) {
for(var prop in obj) {
if(obj.hasOwnProperty(prop)) {