Chapter 2. Strings and Regular Expressions

Here’s a trivia question for your next JavaScript party: how many data types are there in the world’s most popular language?

The answer is eight, but they might not be what you expect. JavaScript’s eight data types are:

  • Number

  • String

  • Boolean

  • BigInt (for very large integers)

  • Symbol (for unique identifiers)

  • Object (the root of every other JavaScript type)

  • undefined (a variable that hasn’t been assigned a value)

  • null (a missing object)

The recipes in this book feature all of these ingredients. In this chapter, you’ll turn your focus to the text-manipulating power of strings.

Checking for an Existing, Nonempty String

Problem

You want to verify that a variable is defined, is a string, and is not empty before you use it.

Solution

Before you start working with a string, you often need to validate that it’s safe to use. When you do, there are different questions you might ask.

If you want to make sure that your variable is a string (not just a variable that can be converted to a string), you use this test:

if (typeof unknownVariable === 'string') {
  // unknownVariable is a string
}

If you want to check that you have a nonempty string (not the zero-length string ''), you can tighten your verification like this:

if (typeof unknownVariable === 'string' && unknownVariable.length > 0) {
  // This is a genuine string with characters or whitespace in it
}

Optionally, you may want to reject strings that are made up of whitespace ...

Get JavaScript Cookbook, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.