Skip to Content
JavaScript Cookbook, 3rd Edition
book

JavaScript Cookbook, 3rd Edition

by Adam D. Scott, Matthew MacDonald, Shelley Powers
July 2021
Intermediate to advanced
535 pages
11h 55m
English
O'Reilly Media, Inc.
Content preview from JavaScript Cookbook, 3rd Edition

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 only, ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Learning JavaScript, 3rd Edition

Learning JavaScript, 3rd Edition

Ethan Brown
JavaScript

JavaScript

T. J. Crowder

Publisher Resources

ISBN: 9781492055747Errata PageSupplemental Content