Reusable User-defined String Functions in JavaScript

Reema Alzohairi
7 min readNov 13, 2019

Do you ever find yourself in need of a basic string function but just can’t find a built-in function that does the job for you? Do you always end up surfing the web, stackoverflow page after the other, until you form a solid function that does the trick for you 101 years later? Look no further as I’m here to save your life.

In this story, I’m sharing with you reusable user-defined JavaScript string functions that I have formed throughout different challenges using different resources. These functions help you save time. Lots and lots of time.

For Example, have you ever needed to extract the first word of a string, say, representing a full name, but couldn’t find a built-in function for it? Well, I got you covered, my friend. The following functions will help you in many situations and save your life as promised!

.isWhiteSpaceOnly( )— Determines if string contains white space only

  • Input: a string.
  • Output: true if the passed string contains white space only and false otherwise.
  • Example: isWhiteSpaceOnly(“ Hello World “) returns false, whereas isWhiteSpaceOnly(“ “) returns true.

.isPrefix( ) — Determines if the passed string contains the second passed string as a prefix (Case Sensitive)

  • Input: a string and a possible prefix.
  • Output: true if the passed string contains the second passed string as a prefix and false otherwise.
  • Example: isPrefix(“image/png“, “image”) returns true, whereas isPrefix(“xxx/image/png“, “image”) returns false.

Note: the function isIncludedInString() is explained below.

.getFirstWord( ) — Returns first word of a string