Reusable User-defined String Functions in JavaScript
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, whereasisWhiteSpaceOnly(“ “)
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, whereasisPrefix(“xxx/image/png“, “image”)
returns false.
Note: the function isIncludedInString()
is explained below.
.getFirstWord( ) — Returns first word of a string
- Input: a string.
- Output: the first word of the string, if the string is not white space only. Otherwise, returns an empty string.
- Example:
getFirstWord(“ Muhammad Ali ”)
returns“Muhammad”
.
.getFirstAndLastWord( ) — Returns the first and the last word of a string
- Input: a string.
- Output: the first and last word of the string, if string is not white space only. Otherwise, returns an empty string. However, If the string has only one word, the output will be the first word only.
- Example:
getFirstAndLastWord(“ Nelson Rolihlahla Mandela ”)
returns“Nelson Mandela”
.
.removeFileNameExtension( ) — Returns the passed file name without the extension
- Input: a string representing a file name.
- Output: the passed string, that represents a file’s name, without the extension when the string is not whitespace only. Otherwise, returns an empty string. If the file name has no extension, the output is the file name as is.
- Example:
removeFileNameExtension(“my_cv.pdf”)
returns“my_cv”
.
.extractPathFromURL( ) —Returns the path of the passed URL
- Input: a string representing a URL.
- Output: the path of the passed URL, whether or not it contains a protocol, a port and/or query parameters. An empty string is returned if the URL contains no path or if it contains whitespace only.
- Example:
extractPathFromURL(“https://hostname.com:portname/pathname/p1/p2/p3?q1=1&q2=2”)
returns“pathname”
.
.isIncludedInString( ) — Determines if a string contains another string within it (Case Sensitive)
- Input: string1 and string2.
- Output: true if string1 contains string2 and false otherwise.
- Example:
isIncludedInString(“The Pacific Ocean”, “Pacific”)
returns true whereasisIncludedInString(“The Indian Ocean”, “Pacific”)
returns false.
Note: the built-in String includes( ) function is not used because it is not supported in IE.
.isIncludedInStringList( ) — Determines if a list of strings contains a particular string (Case Sensitive)
- Input: a list of strings and a string value.
- Output: true if the passed list contains the string value and false otherwise.
- Example:
isIncludedInStringList([‘cat’, ‘dog’], “cat”)
returns true.
Note: the built-in Array includes( ) function is not used because it is not supported in IE.
.hasAnArabicCharacter( ) — Determines if the passed string contains at least one Arabic character
- Input: a string.
- Output: true if the passed string contains at least one Arabic character and false otherwise.
- Example:
hasAnArabicCharacter(“language: العربية”)
returns true.
Note: this function can be applied to any other language just by changing the accepted character unicode range in the function.
.getHttpsVersionOfURL( )— Returns the HTTPS version of a passed URL
- Input: a string.
- Output: the HTTPS version of a URL if the string is not whitespace only. Otherwise, an empty string is returned. If the URL doesn’t contain a protocol or contains a different protocol than HTTP/HTTPS, the URL is returned as is.
- Example:
getHttpsVersionOfURL(“http://github.com/”)
returns“https://github.com/”
.
Note: URL returned will always be in lower case to ensure case sensitivity doesn’t affect the logic.
.concatListAndSeparateBySymbol( ) — Returns a string of all the strings in the passed list separated by the passed symbol
- Input: a list of strings and the separator symbol of choice.
- Output: a string of all the strings in the list concatenated and separated by the passed symbol. If list is empty, an empty string is returned.
- Example:
concatListAndSeparateBySymbol([“You”, “Daniel”, “John”, “, ”])
returns“You, Daniel, John”
.
.replaceEscapedXMLCharactersWithNonEscapedCharacters( ) — Replaces the escaped XML characters in a string, if any, with the corresponding non-escaped characters
- Input: a string.
- Output: the string where all escaped XML characters are replaced by the corresponding non-escaped character.
- Example:
replaceEscapedXMLCharactersWithNonEscapedCharacters(“Bath & Body Works”)
returns“Bath & Body Works”
.
.escapeSpecialCharactersOfRegExpInAString( ) — Escapes all of the special characters, used in regular expression logic, that exist in the passed string
- Input: a string.
- Output: the passed string where all of the special characters of regular expressions are escaped, if any.
- Example:
escapeSpecialCharactersOfRegExpInAString(“How are you?”)
returns“How are you\?”
.
How is this function useful? Say you’re developing a search functionality in your website. The user will use the input field to enter text. You will then fetch the results and as you’re about to display the results say you decided to highlight every occurrence of the searched for text in each search result.
One way to do this will be to use the replace()
function that accepts a regular expression as the first argument, where the text matched by that regular expression will be replaced by whatever text you provide, say a highlighted version of the text. This regular expression needs to be the text the user has entered to match based on it.
What if the user entered the text “hello?”
The question mark is one of many special characters that carry a special meaning in regular expression logic and if you try to create a regular expression directly from what the user has entered, it will never match the literal ?
symbol in the search result. Therefore, if you want to match the entered text as is, you will have to escape all special characters that carry a special meaning in regular expression logic using this magical function.
.replaceSpecialCharactersWithUnderscore( ) — Replaces white spaces, new lines, invalid URL characters and the symbols " '<>&[!@#$%^*(),?":{}<>] with an underscore
- Input: a string.
- Output: the string where every white space, new line, invalid URL character or a symbol from
“ ‘<>&[!@#$%^*(),?”:{}<>]
is replaced with an underscore. - Example:
replaceSpecialCharactersWithUnderscore(“ my<>cv.pdf”)
returns“_my__cv.pdf”
.
This function can be especially useful when, say, you’re uploading files to a server with restrictions on filenames, where particular symbols must be replaced with a particular symbol.
In This function you can add or remove special characters based on your need. You can also change the underscore symbol to whatever symbol your heart desires.
.replaceNonValidURLCharsWithSymbol( ) — Replaces invalid URL characters with the passed symbol
- Input: a string.
- Output: the string where all non-valid URL characters are replaced with the passed symbol.
- Example:
replaceNonValidURLCharsWithSymbol(“ project|1.pdf”, “_”)
returns“_project_1.pdf”
.
Source Code
On Github, I have created 3 repositories. The first repository is a JavaScript repo. You can clone or download the project using the following Github link.
The second repository is a TypeScript repo, which is an Angular project. You can clone or download the project using the following Github link.
Additionally, as suggested by Peter Rietveld, the 3rd repository is a JavaScript repo, where all the functions directly extend the String prototype and can be used as a built-in function once included.
Note: concatListAndSeparateBySymbol() and isIncludedInStringList() functions are not included in this repo as they handle a list of strings rather than string values.