Categories
JavaScript Answers

How to Encode a Javascript Object into a Query String?

Sometimes, we’ve to do convert a JavaScript object’s data into a query string that we can use to make HTTP requests.

In this article, we’ll look at how to encode a JavaScript object into a query string.

URLSearchParams Constructor

We can use the URLSearchParams constructor to let us create query strings easily from a JavaScript object.

It’s available with most current browsers.

For instance, we can write:

const object = {
  a: 1,
  b: 2,
  c: undefined,
  d: null
}
const queryString = new URLSearchParams(object).toString()
console.log(queryString)

We pass in the object that we want to convert to a query string straight into the URLSearchParams constructor.

Then we call toString to return the query string.

And so queryString is:

'a=1&b=2&c=undefined&d=null'

undefined and null are both converted to strings.

The property names are used as keys and the property values are used as the values.

We can also loop through the object and insert the query parameters with the append method:

const object = {
  a: 1,
  b: 2,
  c: undefined,
  d: null
}
const searchParams = new URLSearchParams()
Object.keys(object).forEach(key => {
  searchParams.append(key, object[key])
});
const queryString = searchParams.toString()
console.log(queryString)

We call Object.keys to get the keys in object .

Then we call forEach with the key to get the key from object .

And then call append to add the key and value respectively as arguments.

Then we call searchParams.toString to return the query string.

Therefore, we get the same result as before for queryString .

We can simply the forEach call with the Object.entries method to get an array of arrays of key-value pairs.

So we write:

const object = {
  a: 1,
  b: 2,
  c: undefined,
  d: null
}
const searchParams = new URLSearchParams()
Object.entries(object).forEach(([key, value]) => {
  searchParams.append(key, value)
});
const queryString = searchParams.toString()
console.log(queryString)

to create the query string.

In the forEach callback, we call append with the key and value destructured from the parameter to insert the query parameters.

And so we get the same result as we have before.

Conclusion

We can encode a JavaScript object into a query string with the URLSeacrhParams constructor available with most browsers.

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.