Categories
JavaScript Answers

How to check if a string contains text from an array of substrings in JavaScript?

To check if a string contains text from an array of substrings in JavaScript, we can use the some and includes method.

For instance, we write

if (substrings.some((v) => str.includes(v))) {
  // ...
}

to call some on the substrings array with a callback that calls str.includes with the v entry being looped through in substrings to check if v is in the str string.

If any value v is in str, then some returns true.

Categories
JavaScript Answers

How to split a string into segments of n characters with JavaScript?

To split a string into segments of n characters with JavaScript, we call the match method.

For instance, we write

const str = "abcdefghijkl";
console.log(str.match(/.{1,3}/g));

to call str.match with a regex the matches groups of 1 to 3 characters in the str array.

Categories
JavaScript Answers

How to create an empty typed container array with TypeScript?

To create an empty typed container array with TypeScript, we can declare the type explicitly.

For instance, we write

const arr: Criminal[] = [];

to declare the arr array with the Criminal type.

Categories
JavaScript Answers

How to filter an array from all elements of another array with JavaScript?

To filter an array from all elements of another array with JavaScript, we use the filter and includes methods.

For instance, we write

const arr1 = [1, 2, 3, 4];
const arr2 = [2, 4];
const res = arr1.filter((item) => !arr2.includes(item));
console.log(res);

to call filter with a callback that checks if the item in arr1 isn’t in arr2.

If it’s not, then it’s included in the array returned by filter.

Categories
JavaScript Answers

How to get the last 5 elements, excluding the first element from an array with JavaScript?

To get the last 5 elements, excluding the first element from an array with JavaScript, we call the Math.max and slice methods.

For instance, we write

arr.slice(Math.max(arr.length - 5, 0));

to call Math.max with arr.length - 5 and 0 to return the max number between the 2 numbers.

And then we call slice to return an array with the arr entries between the index returned by max to the last element.