Check if a Value is a String in JavaScript and Node.js

Sometimes you want to ensure a given value is actually a string. For example, you may want to confirm a name property to be a string value.

This tutorial shows you how to detect whether a given value is a string in JavaScript.

Node.js Series Overview

Determine If a Given Value Is a JavaScript String

JavaScript has the typeof operator. It returns the underlying type of a variable. This operator is useful when determining whether a given input value is a string:

/**
 * Determine whether the given `input` is a string.
 *
 * @param {*} input
 *
 * @returns {Boolean}
 */
function isString (input) {  
  return typeof input === 'string' && Object.prototype.toString.call(input) === '[object String]'
}

isString('Hello Marcus')  
// true

isString(123)  
// false

I guess in 99% of all cases you’re totally fine just using the typeof input === 'string' check.

Well, you may ask “why doing the extra Object.prototype.toString.call(input)call” then? You know, shit can go crazy in JavaScript! Sometimes you’re tinkering with prototypes of an instance or assigning a new value to the constructor property. This extra toString comparison is the layer ensuring you’re catching the 1% cases.

Use the @supercharge/strings Package

I’m the maintainer of the @supercharge/strings package providing convenient string utilities. It provides a convenient Str.isString(value) method determining whether a given value is a string:

const Str = require('@supercharge/strings')

const isString = Str.isString('Hello')  
// true

Str.isString(null) // false  
Str.isString(1234) // false  
Str.isString([1, 2, 3]) // false  
// … and so on :)

Enjoy!


Mentioned Resources

Explore the Library

Find interesting tutorials and solutions for your problems.