How to Check if a Value is a String in JavaScript or Node.js

JavaScript comes with handy string methods. What’s missing though is a handy method determining whether a given value is of type “String”. Nonetheless, JavaScript provides methods helping you to detect if a given value is a string value.

Node.js Series Overview

Check if a Value is a String in JavaScript

A common approach is to determine the type of a given input and ensure it’s a string. JavaScript’s typeof operator returns the type of a given value. You can then compare the type against the value 'string':

const input = 'Hello Marcus, I’m a string value'

const isString = typeof input === 'string'  
// true

If you want to be sure that a given value is actually a string, you should add a check on the prototype. This ensures you’re working with a string:

const input = 'Hello Marcus, I’m a string value'

const isString = typeof input === 'string' && Object.prototype.toString.call(input) === '[object String]'  
// true

You may now ask yourself “when would I need to ensure the string prototype of an input?“. Good question! Adding the prototype check is helpful when providing a package that works with strings and needs to ensure that a given input is actually a string.

For example, the @supercharge/strings package provides a isString method doing all the heavy lifting for you.

Use a Package

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

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

Str.isString('Hello Marcus')  
// true

Str.isString(2020)  
// false

Enjoy!


Mentioned Resources

Explore the Library

Find interesting tutorials and solutions for your problems.