7 JavaScript Utility Functions to Improve Your Efficiency

Detect browser, detect function type, convert hyphen-case to camelCase, delete HTML tag in a string and reverse a string, etc.

bitfish
bitfish
Feb 13 · 3 min read
Photo by 🇨🇭 Claudio Schwarz | @purzlbaum on Unsplash

Detect Browser

Different browsers have different navigator.useragent. We can detect browser types by checking this value.

Chrome on Mac OS
Firefox on Mac OS

Detect Function Type

there were two types of functions:

  • functions that were written by users
Native Functions
user-written function

Convert hyp-hens to camelCase

Converting hello-world style strings to helloWorld style strings is a very common requirement. To do this, we can use regular expressions.

Delete HTML tag in string

For security reasons, we often need to remove HTML tags from a string. With a simple regular expression, we can easily accomplish this task.

const stripHTMLTags = str => str.replace(/<[^>]*>/g, '');

Reverse a String

Reverse a string is a common requirement. To do that, we can split a string to an array then reverse the array and join it.

const stripHTMLTags = str => str.replace(/<[^>]*>/g, '');

Format a number to a string with comma

In order to make a large number easier to read, we often add some separator in the middle of the number.

  • 123456789 => 123,456,789

Convert byte units to reasonable units

Inside a computer, the size of a file is often measured in bytes. But if it’s a large number, it’s not readable for humans.

JavaScript in Plain English

Learn the web's most important programming language.

bitfish

Written by

bitfish

Love reading, writing and programming.

JavaScript in Plain English

Learn the web's most important programming language.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade