JS - Other

POST Request with XMLHttpRequest

const xhr = new XMLHttpRequest();
xhr.open("POST", "https://...");
xhr.setRequestHeader("Content-Type", "application/json; charset=UTF-8");
const body = JSON.stringify({
  userId: 1,
  title: "...",
  completed: false
});
xhr.onload = () => {
  if (xhr.readyState == 4 && xhr.status == 201) {
    console.log(JSON.parse(xhr.responseText));
  } else {
    console.log(`Error: ${xhr.status}`);
  }
};
xhr.send(body);

Prevent adding or removing properties in the object

const person = {
    name: 'John', 
    age: 25
};
Object.seal(person);
person.profession = "Programmer";
console.log(person); //Output: {name: 'John', age: 25}

Prevent any changes to an object, including adding, modifying or deleting properties

const person = {
    name: 'John', 
    age: 25
};
Object.freeze(person);
person.name = "Mark";
console.log(person); //Output: {name: 'John', age: 25}

Prevent arrow keys from changing values in a number input

document.getElementById('inputNumber').addEventListener('keydown', function(e) {
    if (e.which === 38 || e.which === 40) {
        e.preventDefault();
    }
});

Preventing onchange being triggered on an input when using tab key on keyboard

$("input").focus().trigger("change", false);

Print Button

  1. Right click on bookmarks bar.
  2. Click on Add page....
  3. Write the title of JS on Name.
  4. Write javascript:window.print().
  5. Click Save.


Click on the page when you want to print the current page.

Random colors

Random RGB colors

function randomRGB() {
  var r = Math.floor(Math.random() * 256);
  var g = Math.floor(Math.random() * 256);
  var b = Math.floor(Math.random() * 256);
  return "rgb(" + r + ", " + g + ", " + b + ")";
}


Random HEX colors

function randomHexColor() {
  var hex = Math.floor(Math.random() * 16777215).toString(16);
  return "#" + hex;
}


Gradient colors

function gradientColor(startColor, endColor, steps) {
  var startRGB = hexToRGB(startColor);
  var endRGB = hexToRGB(endColor);
  var rStep = (endRGB[0] - startRGB[0]) / steps;
  var gStep = (endRGB[1] - startRGB[1]) / steps;
  var bStep = (endRGB[2] - startRGB[2]) / steps;
  var gradientColors = [];
  for (var i = 0; i < steps; i++) {
    var r = Math.round(startRGB[0] + rStep * i);
    var g = Math.round(startRGB[1] + gStep * i);
    var b = Math.round(startRGB[2] + bStep * i);
    gradientColors.push("rgb(" + r + ", " + g + ", " + b + ")");
  }
  return gradientColors;
}

function hexToRGB(hex) {
  var r = parseInt(hex.substring(1, 3), 16);
  var g = parseInt(hex.substring(3, 5), 16);
  var b = parseInt(hex.substring(5, 7), 16);
  return [r, g, b];
}

Random Number in a Specific Range

Math.floor(Math.random() * 5);


// Random number between 0 and 4.
Math.floor(Math.random() * (max - min + 1)) + min;

RegExp

A regular expression is a pattern of characters.

The pattern is used for searching and replacing characters in strings.

The RegExp Object is a regular expression with added Properties and Methods.


/pattern/modifier(s);


Example explained:

  • regexp - The pattern to search for
  • /regexp/ - A regular expression
  • /regexp/i - A case-insensitive regular expression

RegExp (Brackets)

Brackets are used to find a range of characters:


[abc]

Find any character between the brackets


[^abc]

Find any character NOT between the brackets


[0-9]

Find any character between the brackets (any digit)


[^0-9]

Find any character NOT between the brackets (any non-digit)


(x|y)

Find any of the alternatives specified


RegExp (Metacharacters)

Metacharacters are characters with a special meaning:


.

Find a single character, except newline or line terminator


\w

Find a word character


\W

Find a non-word character


\d

Find a digit


\D

Find a non-digit character


\s

Find a whitespace character


\S

Find a non-whitespace character


\b

Find a match at the beginning/end of a word, beginning like this: \bHI, end like this: HI\b


\B

Find a match, but not at the beginning/end of a word


\0

Find a NULL character


\n

Find a new line character


\f

Find a form feed character


\r

Find a carriage return character


\t

Find a tab character


\v

Find a vertical tab character


\xxx

Find the character specified by an octal number xxx


\xdd

Find the character specified by a hexadecimal number dd


\udddd

Find the Unicode character specified by a hexadecimal number dddd

RegExp (Modifiers)

Modifiers define how to perform the search:


/g

Perform a global match (find all)


/i

Perform case-insensitive matching


/m

Perform multiline matching