Categories
JavaScript Answers

How to Get File Extensions with JavaScript?

Sometimes, we may want to get the file extension from a file path.

In this article, we’ll look at how to get the file extension from a path with JavaScript.

String.prototype.split

We can use the JavaScript string’s split method to get the extension from a file path by getting the substring that’s after the last dot in the path.

For instance, we can write:

const ext = '/home/foo/bar.txt'.split('.').pop();
console.log(ext)

We call split with the dot to split the string by the dot.

And then we call pop on it to remove the last item from the split string and return it.

And so ext is 'txt' .

Regex Match

We can also match the file extension with Regex.

For instance, we can write:

const filename = '/home/foo/bar.txt'
const ext = (/[.]/.exec(filename)) ? /[^.]+$/.exec(filename) : undefined;
console.log(ext)

We have the filename with the file path.

Then we look for dots in the filename string with exec .

If there’re any dots in the string, then we check for anything that starts with a dot at the end of a string.

Dollar sign means at the end of the string.

And ^ means starts with.

This would be the file extension.

Therefore, we get the same result as before.

String.prototype.substring and String.prototype.lastIndexOf

We can use a string’s lastIndexOf method to get the index of the last instance of a substring.

And we can combine that with the substring method to extract the file extension substring.

For instance, we can write:

const filename = '/home/foo/bar.txt'
const ext = filename.substring(filename.lastIndexOf('.') + 1, filename.length) || filename;
console.log(ext)

We call substring with filename.lastIndexOf(‘.’) + 1 as the starting index.

And filename.length is the end index.

Then ext should be the same as the other value.

String.prototype.slice and String.prototype.lastIndexOf

We can use slice instead of substring to extract a substring from a JavaScript string.

Therefore, we can use it to get the file extension from a file path with it.

To use it, we write:

const filename = '/home/foo/bar.txt'
const ext = filename.slice((Math.max(0, filename.lastIndexOf(".")) || Infinity) + 1)
console.log(ext)

We find the max between index 0 and the index returned by lastIndexOf to get the last index of the dot.

A path can start with a dot, so it’s possible that the index is 0.

Then we add 1 to get the index excluding the dot itself.

Therefore, we get the same result as we have before.

Conclusion

We can use various JavaScript string methods to extract the file extension from a string.

Categories
JavaScript Answers

How to Get File Extensions with JavaScript?

Sometimes, we may want to get the file extension from a file path.

In this article, we’ll look at how to get the file extension from a path with JavaScript.

String.prototype.split

We can use the JavaScript string’s split method to get the extension from a file path by getting the substring that’s after the last dot in the path.

For instance, we can write:

const ext = '/home/foo/bar.txt'.split('.').pop();
console.log(ext)

We call split with the dot to split the string by the dot.

And then we call pop on it to remove the last item from the split string and return it.

And so ext is 'txt' .

Regex Match

We can also match the file extension with Regex.

For instance, we can write:

const filename = '/home/foo/bar.txt'
const ext = (/[.]/.exec(filename)) ? /[^.]+$/.exec(filename) : undefined;
console.log(ext)

We have the filename with the file path.

Then we look for dots in the filename string with exec .

If there’re any dots in the string, then we check for anything that starts with a dot at the end of a string.

Dollar sign means at the end of the string.

And ^ means starts with.

This would be the file extension.

Therefore, we get the same result as before.

String.prototype.substring and String.prototype.lastIndexOf

We can use a string’s lastIndexOf method to get the index of the last instance of a substring.

And we can combine that with the substring method to extract the file extension substring.

For instance, we can write:

const filename = '/home/foo/bar.txt'
const ext = filename.substring(filename.lastIndexOf('.') + 1, filename.length) || filename;
console.log(ext)

We call substring with filename.lastIndexOf(‘.’) + 1 as the starting index.

And filename.length is the end index.

Then ext should be the same as the other value.

String.prototype.slice and String.prototype.lastIndexOf

We can use slice instead of substring to extract a substring from a JavaScript string.

Therefore, we can use it to get the file extension from a file path with it.

To use it, we write:

const filename = '/home/foo/bar.txt'
const ext = filename.slice((Math.max(0, filename.lastIndexOf(".")) || Infinity) + 1)
console.log(ext)

We find the max between index 0 and the index returned by lastIndexOf to get the last index of the dot.

A path can start with a dot, so it’s possible that the index is 0.

Then we add 1 to get the index excluding the dot itself.

Therefore, we get the same result as we have before.

Conclusion

We can use various JavaScript string methods to extract the file extension from a string.

Categories
JavaScript Answers

How to Clone a JavaScript Date Object?

Sometimes, we may need to clone a JavaScript date object in our code.

In this article, we’ll look at ways to clone a date object in our JavaScript code.

Date.prototype.getTime and the Date Constructor

We can pass a timestamp constructor to the Date constructor.

So we can get the timestamp from the existing date object and then pass that into the Date constructor.

For instance, we can write:

const date = new Date();  
const copiedDate = new Date(date.getTime());  
console.log(copiedDate)

We call getTime to return the timestamp from the date object.

Then we pass that to the Date constructor to create the new date object.

And copiedDate is a new date object.

Date.prototype.valueOf

We can also get the timestamp with the valueOf method of a date object.

For instance, we can write:

const date = new Date();  
const copiedDate = new Date(date.valueOf());  
console.log(copiedDate)

And we get the same result as the previous example.

The Unary Plus Operator

Another way to get the timestamp from a JavaScript date object is to use the unary plus operator.

For instance, we can write:

const date = new Date();  
const copiedDate = new Date(+date);  
console.log(copiedDate)

And we get the same result as the previous examples.

Pass in the Date Object into the Date Constructor Directly

The Date constructor also accepts a date object directly.

So we can use it to create a clone of our original date object.

For instance, we can write:

const date = new Date();  
const copiedDate = new Date(date);  
console.log(copiedDate)

And we get the same result as before.

Conclusion

There’re several ways we can use th clone a date object in JavaScript.

One way is to get the timestamp with various operators or methods and pass that into the Date constructor.

The other way is to pass in the Date instance itself to the Date constructor to create a new Date instance.

Categories
JavaScript Answers

How to Remove Spaces From a String Using JavaScript?

There’re many occasions where we may want to remove spaces from a string with JavaScript.

In this article, we’ll look at how to remove spaces from a string with JavaScript.

Search for Spaces with Regex and Replace Them

We can search for spaces with regex and replace them with the JavaScript string’s replace method.

For instance, we can write:

const result = ' abc '.replace(/ +/g, '');
console.log(result)

to remove one or more spaces with the replace method.

We just have a space with a plus sign after it to search for one or spaces.

Then g flag lets us search for all instances of spaces in a string.

Therefore, result should be 'abc' .

Alternatively, we can search for instances of one or more spaces and replace them with:

const result = ' abc '.replace(/\s+/g, '');
console.log(result)

Also, we can search for instances of single spaces and replace them with:

const result = ' abc '.replace(/ /g, '');
console.log(result)

And we get the same result.

Also, we can use the \s pattern to search for a single space and replace them.

For instance, we can write:

const result = ' abc '.replace(/\s/g, '');
console.log(result)

to get the same result.

The fastest way to replace all empty spaces is:

const result = ' abc '.replace(/ /g, '');
console.log(result)

for short strings.

And for long strings:

const result = ' abc '.replace(/ +/g, '');
console.log(result)

is fastest.

String.prototype.split

We can also split strings with the split method using a space as a separator.

And then we join the split string array back together with join .

For instance, we can write:

const result = ' abc '.split(' ').join('');
console.log(result)

And we get the same result as the previous examples.

Conclusion

We can use the replace method with a regex to search for all spaces and replace them with empty strings to remove all whitespace from a string.

Also, we can use the split method to split a string by a whitespace character string and join it back together with join to do the same thing.

Categories
JavaScript Answers

How to Split a JavaScript Array Into Chunks?

Sometimes, we may want to divide JavaScript arrays into chunks in our code.

In this article, we’ll look at how to split a JavaScript array into chunks.

Array.prototype.slice

We can use the slice array instance method to extract a chunk of an array with the start and end index.

The item at the start index is included, but the item at the end index isn’t.

For instance, we can write:

const array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
const chunk = 2;
let tempArray = []
const result = []
for (let i = 0, j = array.length; i < j; i += chunk) {
  tempArray = array.slice(i, i + chunk);
  result.push(tempArray)
}
console.log(result)

We have the array array that we want to divide into chunks.

chunk specifies the length of each chunk.

tempArray has the extracted array chunk.

And we have a for loop to let us loop through array to extract the chunks.

We increment i by chunk in each iteration to skip to the start of the next chunk.

Then in the loop body, we call slice with i and i + chunk to return each chunk.

And we call push with tempArray to add it to the result array.

Therefore, result is:

[
  [
    1,
    2
  ],
  [
    3,
    4
  ],
  [
    5,
    6
  ],
  [
    7,
    8
  ],
  [
    9,
    10
  ]
]

Array.prototype.concat and Array.prototype.map

We can use the concat array method to append one or more items to an array.

And we can use map to map the values of the original array into array chunks.

For instance, we can write:

const array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
const chunk = 2;
const result = array.map((elem, i) => {
  return i % chunk ? [] : [array.slice(i, i + chunk)];
}).flat()
console.log(result)

We have the same array and chunk size as the previous example.

Then we call array.map with a callback that checks if index i is evenly divisible by chunk .

If it is, then we return the array chunk with the callback with slice .

Otherwise, we return an empty array.

We then call flat to flatten the returned array to flatten the arrays one level to get what we want.

Since we’ve to loop through the whole array , this is less efficient than the for loop.

Therefore, result should be the same as what we have before.

Conclusion

We can split an array into chunks with various JavaScript array methods.