Categories
JavaScript Answers

How to Count the Number of Substring Occurrences in a JavaScript String?

Sometimes, we’ve to count the number of occurrences of a substring in our JavaScript strings.

In this article, we’ll look at how to count the number of substring occurrences in a JavaScript string.

String.prototype.match

The string match method lets us find the substrings with the given regex pattern in the string it’s called on.

Therefore, we can use it to find the number of substring occurrences in a JavaScript string.

To use it, we write:

const str = "This is a string.";
const count = [...(str.match(/is/g) || [])].length;
console.log(count);

We have the str string.

And we call match on it with the substring we’re looking for and the g flag to look for all instances of the substring in the string.

If there’re no matches, it returns undefined , so we’ve to add || [] to return an empty array in that case.

Then we get the length of the array to get the number of occurences.

So count is 2 since there’re 2 instances of 'is' in the string.

String.prototype.split

We can use the split method to split a string by its separator.

So we can use split to split the string by the substring we’re looking for and subtract that by 1 to get the number of instances of a substring.

To do this, we write:

const str = "This is a string.";
const count = str.split('is').length - 1;
console.log(count);

We call split with 'is' to split the str string with'is' as the separator.

Then we’ve to minus 1 from the returned length to get the right result.

Conclusion

To count the number of instances of a substring in a string, we can either split the string or search for it using a regex.

Categories
JavaScript Answers

How to Duplicate an Array in JavaScript?

Duplicating an array is something that we’ve to do a lot in our JavaScript apps.

In this article, we’ll look at how we can duplicate arrays in JavaScript.

Loops

One way to duplicate a JavaScript array is to use a loop.

For instance, we can use a for-of loop by writing:

const arr = [1, 2, 3]
const clone = []

for (const a of arr) {
  clone.push(a)
}
console.log(clone)

We loop through arr with a for-of loop and call push on clone to add the items into clone .

And so clone should have the same entries as arr .

We can also use a while loop to loop through the array.

For example, we write:

const arr = [1, 2, 3]
const clone = []

let i = 0;
while (i < arr.length) {
  clone.push(arr[i])
  i++
}
console.log(clone)

We get the item by its index with the square brackets and do the same push operator.

Then we increment the i value to move to the next element in the next iteration.

Also, we can use a plain for loop to do the same thing:

const arr = [1, 2, 3]
const clone = []

for (let i = 0; i < arr.length; i++) {
  clone.push(arr[i])
}
console.log(clone)

We put the index changing logic all in the parentheses.

Array.prototype.slice

The slice method returns a clone of the array we’re calling it on if there’re no arguments passed in.

For instance, we can write:

const arr = [1, 2, 3]
const clone = arr.slice()
console.log(clone)

And we get the same result as before.

Array.from

The Array.from method is a static array method that lets us create an array from another array.

Therefore, we can use it to create a clone of the array.

Its first argument is an array or an array-like object we want to create the derived array from.

And the 2nd argument is a function that lets us map the values of the object or array in the first argument and map them to different values.

For example, we can write:

const arr = [1, 2, 3]
const clone = Array.from(arr, a => a)
console.log(clone)

We call Array.from with the arr array.

And the function just returns the value as is.

So we get the same result as in the previous example.

Array.prototype.concat

The concat array instance method also returns an array by combining the array that it’s called with the one that we pass into the argument.

So to use it to clone an array, we can write:

const arr = [1, 2, 3]
const clone = arr.concat([])
console.log(clone)

or:

const arr = [1, 2, 3]
const clone = [].concat(arr)
console.log(clone)

The order doesn’t matter since we only have arr and an empty array.

Either way, we get a clone of arr returned.

Spread Operator

The spread operator also lets us duplicate an array.

For instance, we can write:

const arr = [1, 2, 3]
const clone = [...arr]
console.log(clone)

to clone arr with the spread operator.

So we get the same result as in the previous examples.

Array.prototype.map

The map method lets us return an array that has the values mapped from the original array.

To return a clone of the original array, we just pass in a callback that returns the values being iterated through as-is.

For instance, we can write:

const arr = [1, 2, 3]
const clone = arr.map(a => a)
console.log(clone)

to call map with a call that returns the value being iterated through as-is.

And we get the same result as before.

Conclusion

There’re many ways to clone an array with JavaScript.

The easiest way would be to use the spread operator.

It’s also very fast.

Categories
JavaScript Answers

How to Access the First Property of a JavaScript Object?

In our JavaScript programs, sometimes we only want to access the first property of a JavaScript object.

In this article,e we’ll look at various ways we can access only the first property of a JavaScript object.

Object.keys

The Object.keys method returns an array with the string keys of an object.

So we can access the first property in an object by writing:

const obj = {
  a: 1,
  b: 2
};
const [prop] = Object.keys(obj)
console.log(obj[prop])

We have the obj object with some properties.

And we call Object.keys and destructure the first key from the returned array and assign it to prop .

And then we get the value of the first property returned with obj[prop] .

So we get 1 from the console log.

for-in Loop and break

We can use the for-in loop to loop through an object and break after the first iteration.

For instance, we can write:

const obj = {
  a: 1,
  b: 2
};

for (const prop in obj) {
  console.log(obj[prop])
  break;
}

We have the for-in loop and log the first property value returned.

prop has the property key string.

Then we use break to stop iterating.

Object.values

We can use the Object.values method to get the values from an object.

For instance, we can write:

const obj = {
  a: 1,
  b: 2
};

const [value] = Object.values(obj)
console.log(value)

If we just want the first property value, then we can just use Object.values and destructure it from the returned array.

Object.entries

We can use the Object.entries method to return an array of arrays of key-value pairs.

For instance, we can write:

const obj = {
  a: 1,
  b: 2
};

const [
  [key, value]
] = Object.entries(obj)
console.log(key, value)

to get the first key-value pair from the returned array.

We just destructure it from the nested array.

And so key is 'a' and value is 1.

Conclusion

We can use JavaScript object static methods or the for-in loop to get the first property from a JavaScript object.

Categories
JavaScript Answers

How to Check Whether a JavaScript Object is a Date Object?

Sometimes, we’ve to check if a JavaScript object is a date object.

In this article, we’ll look at ways to check whether a JavaScript object is a date object.

Checking for Methods that Date Objects Have

We can check for methods that date objects have.

To do this, we can use the typeof operator.

For instance, we can write:

const date = new Date(2021, 1, 1);
console.log(typeof date.getMonth === 'function')

We check that the getMonth method is a function by using the typeof operator to see if it returns 'function' .

If it’s true , then we know it’s likely that date is a Date instance.

The console log should log true , so it’s a good chance that it’s a Date instance.

The instanceof Operator

A more accurate check is to check whether the object is created from the Date constructor.

If it is, then we know it must be a Date instance.

For instance, we can write:

const date = new Date(2021, 1, 1);
console.log(date instanceof Date)

to check if date is created from the Date constructor with the instanceof operator.

The left operand is the object we’re checking.

And the right operand is the constructor we’re checking for.

Since date is created from Date , the console log should log true .

To check if an object is created from the Date constructor across frame boundaries, we can convert it to a string with the toString method and check its contents.

To do this, we write:

const date = new Date(2021, 1, 1);
console.log(Object.prototype.toString.call(date) === '[object Date]')

We call toString as Object.prototype.toString.call since toString maybe overridden with our own methods.

By calling it this way, we make sure we call the built-in toString method rather than the one we created.

Check for Invalid Date

If we pass in something that can’t be parsed to a date into the Date constructor, then it returned 'Invalid Date' when the object is converted to a string.

So we can check for this by writing:

console.log(new Date('abc').toString() === 'Invalid Date')

We pass in 'abc' into the Date constructor, which can’t be parsed to a date.

So when we call toString , it returns ‘Invalid Date’ .

Therefore, the console log should log true .

Conclusion

There’re several ways we can use to check for a valid date object or an invalid one with JavaScript.

Categories
JavaScript Answers

How to Subtract Days from a JavaScript Date?

Subtract dates from a date is an operation that we’ve to do often in our JavaScript code.

In this article, we’ll look at how to subtract days from a JavaScript date.

Date.prototype.getDate and Date.prototype.setDate

We can use the getDate method to get the date.

And then use the setDate method to set the date by manipulating the date we got from getDate and passing the returned value into setDate .

For instance, we can write:

const date = new Date(2021, 1, 1);
date.setDate(date.getDate() - 5);
console.log(date)

to subtract 5 days from February 1, 2021.

We call getDate from the date object.

Then we subtract 5 days from it.

And then we pass that into setDate .

Therefore date is now 'Wed Jan 27 2021 00:00:00 GMT-0800 (Pacific Standard Time)’ .

date is changed in place with setDate .

Date.prototype.getTime and Date.prototype.setTime

We can also call setTime to set the timestamp of the date instead of the days.

This is more precise since the time is in milliseconds.

To do this, we write:

const dateOffset = (24 * 60 * 60 * 1000) * 5;
const date = new Date(2021, 1, 1);
date.setTime(date.getTime() - dateOffset);
console.log(date)

We have the dateOffset in milliseconds.

And we have the same date object as in the previous example.

In the 3rd line, we call setTime with the timestamp value returned from getTime , which is in milliseconds.

And we subtract that by dateOffset , which is 5 days in milliseconds.

date is changed in place with setTime .

So date in string form is now ‘Wed Jan 27 2021 00:00:00 GMT-0800 (Pacific Standard Time)' .

moment.js

We can use the moment.js library to make date manipulation easier.

For instance, we can write:

const dateMnsFive = moment('2021-02-01').subtract(5, 'day');
console.log(dateMnsFive.toDate())

We create a moment object for February 1, 2021 with moment .

The returned object has the subtract method to let us subtract the time amount we want.

The first argument is the amount.

And the 2nd argument is the unit of the amount to subtract from.

Then we can convert that back to a native JavaScript date object with toDate .

And so we get the same result as the previous examples.

Moment objects also come with the toISOString method.

For instance, we can write:

const dateMnsFive = moment('2021-02-01').subtract(5, 'day');
console.log(new Date(dateMnsFive.toISOString()))

We can pass in the string returned by toISOString to the Date constructor to get a native date object back.

And so we get the same result as the previous example.

Conclusion

We can subtract days from a date with native JavaScript date methods.

To make the work easier, we can also use a library like moment.js to help us.