Useful Code Snippets & Commands

Some of the contents in this page are not originally from me, every function or command that I found it very useful or something that I create by myself, I will put it in here.


< Back to homepage
Shell: Using "grep" to Extract URLs from Junk Data

credit: @imranparray101

cat file | grep -Eo "(http|https)://[a-zA-Z0-9./?=_-]*"*

curl http://host.xx/file.js | grep -Eo "(http|https)://[a-zA-Z0-9./?=_-]*"*

#shell
JavaScript: Check Vowel in a Sentence
function vowels(str) {
  const matchesVowel = str.match(/[aiueo]/gi);
  return matchesVowel?.length || 0;
}

#javascript
JavaScript: Reverse Integer
function reverseInt(num) {
  if (num < 0) return -reverseIntOpt(-num);
  const reversed = num.toString().split('').reverse().join('');

  return Number(reversed);
}

#javascript
JavaScript: Get Random Item From an Array
const items = [1, 2, 3, 4, 5, 6, 7, 8, 9];

function getRandomItem(arr) {
  return arr[Math.floor(Math.random() * arr.length)];
}

getRandomItem(items);

#javascript
JavaScript: Get Random Number
function getRandomNumber(minVal, maxVal) {
  return Math.floor(Math.random() * (maxVal - minVal + 1)) + minVal;
}
getRandomNumber(5, 99);

#javascript
JavaScript: Intersection of Arrays
const arr1 = ['a', 'b', 'c', 'd', 'e'];
const arr2 = ['b', 'e'];

function intersectionArray(a, b) {
  return a.filter(Set.prototype.has, new Set(b));
}

intersectionArray(arr1, arr2); // ["b", "e"]

#javascript
JavaScript: Union of Arrays
const arr1 = ['a', 'b', 'c'];
const arr2 = ['a', 'c', 'b', 'd', 'e'];

const unionArr = (a, b) => Array.from(new Set([...a, ...b]));

unionArr(arr1, arr2); // ["a", "b", "c", "d", "e"]

#javascript
JavaScript: Remove Specific Object Key from Array of Objects
const allUser = [
  {
    id: 1,
    name: 'John',
    password: '1234',
  },
  {
    id: 2,
    name: 'Doe',
    password: 'abcd',
  },
];

// exclude `password` field
const users = allUser.map(({ password, ...rest }) => rest);
return users;

#javascript
Shell: Docker Stop All Running Containers
docker stop $(docker ps -q)

#shell
Shell: rsync Local Files to Server
rsync -arvz -e 'ssh -p 22' \
source_dir/{dir1,dir2} \
username@ip_address:/destination_dir

#shell