Categories
JavaScript Answers

How to Check if a Variable is a String in JavaScript?

Checking if a variable is a string is something that we’ve to do a lot in JavaScript since JavaScript variables can store data of any type.

In this article, we’ll look at how we can check if a variable is a string in JavaScript.

The typeof Operator

The JavaScript typeof operator is useful for checking if a variable is a string.

For instance, we can write:

const booleanValue = true;
const numericalValue = 123;
const stringValue = "abc";
const stringObject = new String("abc");
console.log(typeof booleanValue)
console.log(typeof numericalValue)
console.log(typeof stringValue)
console.log(typeof stringObject)

We use the typeof operator before variables to check what they return.

The first console.log should log 'boolean' .

The 2nd console.log should log 'boolean' .

The 3rd console.log should log 'string' .

And the 4th console.log should log 'object' .

We shouldn’t use the String constructor since it doesn’t return the type we expect for a string.

Instead, we should always use string literals.

toString

We can use a string’s toString method to check if it’s a string.

For instance, we can write:

const booleanValue = true;
const numericalValue = 123;
const stringValue = "abc";
const stringObject = new String("abc");

const isString = (x) => { return Object.prototype.toString.call(x) === "[object String]" } console.log(isString(booleanValue)) console.log(isString(numericalValue)) console.log(isString(stringValue)) console.log(isString(stringObject))


We call `toString` from the `Object.prototype` with the parameter `x` and see if it returns `'[object String]'` .

If `x` is a string, then its `toString` method inherited from `Object.prototype` should return `'[object String']` .

Therefore, the first 2 console logs log `false` .

And the last 2 logs `true` .

### **Lodash**

Lodash has a `isString` method to check if a variable is a string.

For instance, we can write:

const booleanValue = true; const numericalValue = 123; const stringValue = "abc"; const stringObject = new String("abc");

console.log(_.isString(booleanValue))
console.log(_.isString(numericalValue))
console.log(_.isString(stringValue))
console.log(_.isString(stringObject))
```

It works with both string literals and string wrapper objects, so the first 2 console log log `false` .

And the last 2 log `true` .

### Conclusion

There are many ways to check whether a JavaScript variable holds a string.

One way is to use the `typeof` operator. The other to check the return result of `toString` .

Lodash also has the `isString` method to check if a variable is a string.
Categories
JavaScript Answers

How to Format Numbers as a Currency String in JavaScript?

Formatting numbers as currency stings is something that we have to do sometimes in our JavaScript apps.

In this article, we’ll look at how to format numbers as currency strings with JavaScript.

The Intl.NumberFormat Constructor

We can use the Intl.NumberFormat constructor that comes with most browsers to format a number into a currency string.

For instance, we can write:

const formatter = new Intl.NumberFormat('en-US', {
  style: 'currency',
  currency: 'USD',
});
const str = formatter.format(1500);
console.log(str)

We pass in the locale and an object with formatting options arguments of the constructor.

style is set to 'currency' to format a number into a currency string.

currency is set to 'USD' to let us format it the number into USD format.

Then we just call format with the amount and assign the result to str .

And so str is ‘$1,500.00’ .

We can also set the minimumFractionDigits and maximumFractionDigits properties in the object to set the min and max number of decimal places to return.

toLocaleString

JavaScript strings come with the toLocaleString method that lets us format numbers into currency strings.

For instance, we can write:

const str = (1500).toLocaleString('en-US', {
  style: 'currency',
  currency: 'USD',
});
console.log(str)

The arguments are the same as the format method.

And we get the same result as Intl.NumberFormat .

Intl.NumberFormat is 70 times faster than toLocaleString if we have lots of numbers to format, so it’s better to use Intl.NumberFormat if we need to format lots of numbers.

Regex Replace

We can use the toFixed method to return a string with 2 decimal places.

Then we can use replace to add thousands separators to the returned string.

For instance, we can write:

const str = (123.45).toFixed(2).replace(/d(?=(d{3})+.)/g, '$&,');

The ?= is a lookahead assertion to let us get groups of 3 digits in a string behind one digit.

So if it sees groups of 3 digit behind another digit, then it’ll add a comma in between the digits.

$& indicates that we want to do the replacement in the existing string and not replace characters.

Therefore, str should be '123.45' .

Conclusion

We can format numbers into currency strings with JavaScript by using built-in methods.

Also, we can use the replace method to add commas between groups of 3 digits.

Categories
JavaScript Answers

How to Get the Size of the Screen, Current Web Page, or Browser Window with JavaScript?

Getting the screen size is important if we want to create responsive web apps.

Therefore, this is an operation that’s frequently done within JavaScript web apps.

In this article, we’ll look at how to get the size of the screen, web page, or browser window with JavaScript.

Use the window.screen Object to Get a Screen’s Dimensions

The window.screen object lets us get the height and width of the browser’s screen with the height and width properties respectively.

For instance, we can write:

console.log(window.screen.height,
  window.screen.width)

to get the height and width of the screen that the app is currently on.

Window innerWidth and innerHeight Properties

The window.innerWidth and window.innerHeight properties let us get the current width and height of the frame that the app is currently being displayed in.

It doesn’t include dimensions of anything outside the frame like toolbars, etc.

For instance, we can write:

console.log(window.innerWidth, window.innerWidth)

log both the width and the height of the frame.

Window outerWidth and outerHeight Properties

The window.outerWidth and window.outerHeight properties let us get the current width and height of the frame that the app is currently being displayed in.

It includes dimensions of the whole frame including the toolbars and scrollbars.

For instance, we can write:

console.log(window.innerWidth, window.innerWidth)

log both the width and the height of the frame with the toolbars and scrollbars.

Use the window.screen Object to Get the Available Space of the Screen

We can use the window.screen object to get the available space of the screen with the availWidth and availHeight properties.

For instance, we can write:

console.log(window.screen.availWidth, window.screen.availHeight)

to get the available width and height of the screen that’s available to the browser.

So the operating system’s menubars and taskbars dimensions will be subtracted from the screen’s resolution.

Get Screen Dimensions From the document Object

Also, we can get the screen’s dimensions from the document object.

For instance, we can write:

console.log(document.body.clientWidth, document.body.clientHeight)

to get the width and height of the body element.

clientWidth is calculated from the CSS width +CSS padding — height of the vertical scrollbar.

clientHeight is calculated from the CSS height +CSS padding — height of the horizontal scrollbar.

Conclusion

There are several ways to get the dimensions of the screen or the browser window with JavaScript.

Categories
JavaScript Answers

How to Trim Off the Last Character in a JavaScript String?

Trimming off the last character in a JavaScript string is something that we’ve to do often.

In this article, we’ll look at how to trim off the last character in a JavaScript string.

String.prototype.substring

We can use the substring method available in a string instance to return a substring of the string it’s called on.

For instance, we can use it by writing:

let str = "abc";
str = str.substring(0, str.length - 1);
console.log(str);

We have the str string which we want to remove the last character from.

Then we call substring with the start and end indexes which we want to extract from.

Then we assign the returned value back to str .

The end index itself is excluded from the string, so we need to subtract one from the end index we want to extract the substring we want.

Therefore, str is 'ab' in the last line of the code.

String.prototype.slice

A string also comes with the slice method.

For instance, we can write:

let str = "abc";
str = str.slice(0, -1);
console.log(str);

slice also takes the start and end indexes respectively.

But we can use the negative indexes which start with -1 for the last character, -2 for the 2nd last character, and so on.

Like with substring , slice excludes the character at the end index from the returned string.

Therefore, we get the same result with slice we we do with substring .

slice with lastIndexOf

The lastIndexOf method returns the last index of a given character.

So we can write:

let str = "abc";
str = str.slice(0, str.lastIndexOf("c"));
console.log(str);

We pass 'c' to lastIndexOf to get the last index of the str string.

So we see 'ab' as the value of str in the last line.

The split, pop, and join Methods

Also, to remove the last character from a JavaScript string, we can split the string into an array, then call pop to remove the last item from the array, then use join to join the character array back into a string.

To do this, we write:

let str = "abc";
const strArr = str.split("")
strArr.pop();
str = strArr.join('')
console.log(str);

We call split with an empty string to split str into an array of characters and we store that in strArr .

Then we call pop on strArr to remove the last element from strArr .

And then we call join to combine the character array back to a string.

Since strings are iterable objects, we can just use the spread operator to spread it into a string.

For instance, we can write:

let str = "abc";
const strArr = [...str]
strArr.pop();
str = strArr.join('')
console.log(str);

Conclusion

There are many ways to trim off the last character from a string with JavaScript.

Categories
JavaScript Answers

How to Format a JavaScript Date?

Formatting dates is something that we have to do a lot in JavaScript apps.

In this article, we’ll look at how to format dates with JavaScript.

The Intl.DateTimeFormat Constructor

The easiest way to format a date is with the Intl.DateTimeFormat constructor.

It returns an object with the format method.

For instance, we can write:

const date = new Date()
const dateFormat = new Intl.DateTimeFormat('en');
const formattedDate = dateFormat.formatToParts(date);
console.log(formattedDate)

The formatToParts method will get the parts of the date object as an array.

As a result, we get:

[
  {
    "type": "month",
    "value": "2"
  },
  {
    "type": "literal",
    "value": "/"
  },
  {
    "type": "day",
    "value": "12"
  },
  {
    "type": "literal",
    "value": "/"
  },
  {
    "type": "year",
    "value": "2021"
  }
]

as the value of formattedDate .

Then we can combine the values the way we like in a string.

To do that, we write:

const date = new Date()
const dateFormat = new Intl.DateTimeFormat('en');
const formattedDate = dateFormat.formatToParts(date);
const formattedDateObj = formattedDate.reduce((formattedDateObj, {
  type,
  value
}) => ({
  ...formattedDateObj,
  [type]: value
}), {});
console.log(`${formattedDateObj.year}-${formattedDateObj.month}-${formattedDateObj.day}`)

We create the formattedDateObj object from the array by calling reduce with a callback.

The callback takes the formattedDateObj , which is the object we have created so far.

The 2nd parameter is an object with the type and value properties from the array.

We return an object with a copy of the formattedDateObj object with the new property added to it at the end.

The 2nd argument of reduce is an empty object.

We set it to an empty object, so we can convert the entries of the formattedDate array and put it into the empty object.

Then we can combine the properties into our own date string as it’s done in the last line.

Another way to get the parts of a date is to extract the parts of a date individually.

For instance, we can write:

const d = new Date();
const ye = new Intl.DateTimeFormat('en', {
  year: 'numeric'
}).format(d);
const mo = new Intl.DateTimeFormat('en', {
  month: 'short'
}).format(d);
const da = new Intl.DateTimeFormat('en', {
  day: '2-digit'
}).format(d);
console.log(`${da}-${mo}-${ye}`);

We use the IntlDateTimFormat constructor with the locale and an object to specify how we format the object as arguments.

'numeric' returns the 4 digit year.

'short' returns a month abbreviation.

And '2-digit' returns the 2 digit date.

So we should get something like:

'12-Feb-2021'

returned.

The toLocaleDateString Method

The toLocaleDateString method also lets us format a date easily.

For instance, we can write:

const options = {
  weekday: 'long',
  year: 'numeric',
  month: 'long',
  day: 'numeric'
};
const today = new Date();
console.log(today.toLocaleDateString("en-US", options));

We have the options object to specify how a date is formatted.

The options are the same as in the previous example.

toLocaleString takes the locale and the options as arguments.

Therefore, we get:

'Friday, February 12, 2021'

Conclusion

We can format JavaScript date objects easily with the Intl.DateTimeFormat constructor or the toLocaleDateString method.