Indispensable JavaScript Hacks For Manipulating Strings

kirill ibrahim
JavaScript in Plain English
8 min readOct 17, 2021

--

JavaScript Strings Hacks Banner Image

Introduction:

Strings are the most basic data type in every programming language. JavaScript Strings are useful for storing texts which can contain characters, numbers, and Unicode. Many programming languages are open enough to allow programmers to do things multiple ways for a similar outcome. JavaScript is also the same.

Many developers have found many hacks after manipulating Strings in JavaScript. Today, I will share some hacks that are simply indispensable when it comes to manipulating Strings in JavaScript.

We will go through the following hacks or paradigms in the article:

1. How to check if a String is empty?

2. How to reverse a String?

3. How to remove substring from a String?

4. How to insert space before capital letters?

5. How to remove spaces from a string?

6. How to make the first letter of a String uppercase?

7. How to convert a String into a boolean?

8. How to remove a character from a String?

1. How to Check if a String is Empty?

We will introduce different methods for checking if the String is empty.

Use the === operator to check if the String is empty

We can use the strict equality operator (===) to check whether a String is empty or not. The comparison data=== "" will only return true if the data type of the value is a String, and it is also empty; otherwise, it will return false.

Example:

Output:

false
false
false
false
false
true

Note: Do not use equality comparator == because data == "" will return true if data is 0 or false but not only the empty String "".

Example:

Output:

true
true
true

Use the length property to check if the String is empty

This is a different way to check for a JavaScript empty String. If the length is zero, then we know that the String is empty.

Example:

Example Use the length property to check if the String is empty

Output:

false
true
false

Convert the variable to boolean to check if the String is empty

There are two ways to convert variables to a boolean value. First by dual NOT operators (!!), and second by typecasting (Boolean(value)).

Boolean(str);!!str;

The str is a variable. It returns false for null, undefined, 0, 000, "", false. It returns true for not empty String and whitespace.

Example:

Example Convert the variable to Boolean to check if the String is empty

Output:

true
false
true
false

2. How to Reverse a String?

There are different ways to reverse a String in JavaScript.

For example:

  • "worldmajor" -> "rojamdlrow"
  • "this is an example" -> "elpmaxe na si siht"

Use built-in methods to reverse a String:

  • Convert a String object into individual array elements using the split() that split a String into an array.
  • We will use the reverse() function to reverse the array of characters.
  • We will use the join() function to join array elements into a single String.

Example:

Example on built-in methods to reverse a string

Use the spread operator to reverse a String:

We will use the same approach above, but the only difference is that we will use the spread operator to convert a String into an array of characters instead of the split() function. Learn more about the spread operator here.

Example:

Example on spread operator to reverse a string

Use for-loop to reverse a String:

The most straightforward way is to loop on a String.

Example:

Example on For loop to reverse a string

Another example with the new for-loop syntax is introduced in ES6:

Example:

Use recursion to reverse a String:

We set up a function, then it recursively calls itself until it reaches our goal.

Example:

Example on Recursion to reverse a string

Another example of recursion by using a ternary operator:

Example on a ternary operator to reverse a string

3. How to Remove Substring from a String?

JavaScript has two popular methods to remove a substring from a String. Every method below will have a code example, which you can run on your machine.

Use the replace() method to remove a specific substring from a String:

The replace() function is a built-in function in JavaScript. It replaces a part of the given String with another String or a regular expression. It returns new a String from a given String. So the original String will remain unchanged.

Syntax of replace():

Txt.replace(Specificvalue, Newvalue)

The Specificvalue is required, that will be replaced by the new value and Newvalue is required.

Example:

replace() method to remove specific substring

Use the replace() method with regex to remove all occurrences of the specific substring from a string

A regular expression is used instead of the Specificvalue along with the global property.

Example:

replace() method with regex

Use the substr() method to extract a specific substring from a string

The substr() function is a built-in function in JavaScript. It is used to extract a substring from a given String, or returns a portion of the String, start at the specified index and extend for a given number of characters.

Syntax:

String.substr(startIndex, length)

The startIndex is required. The length is optional, the length of the String to be selected from that Startindex, and if it is not specified, it extracts to the rest of the String.

Example:

substr() method to extract a specific substring

4. How to Insert Space Before Capital Letters?

Let’s imagine that you get a response from APIs a text to display it, then you find there is no space between the end of a word and the beginning of another word as an example requirementsMost I want to place a space between requirement and Most .

Add a space before every uppercase character

You can just add a space before every uppercase character and trim off the leading and trailing spaces:

text = text.replace(/([A-Z])/g, ' $1').trim()

Find each occurrence of a lowercase character followed by an uppercase character

This will find each occurrence of a lowercase character followed by an uppercase character, and insert a space between them:

text = text.replace(/([a-z])([A-Z])/g, '$1 $2');

For special cases when 2 consecutive capital letters occur (Eg: ATest) use the code below:

text = text.replace(/([A-Z])([A-Z])/g, '$1 $2');

5. How to Remove Spaces from a String?

To remove spaces from String, let’s take look at the following example:

Input: / world major .net/Output: /worldmajor.net/

JavaScript has different methods to remove spaces from a String. we will demonstrate two ways to remove spaces from a String, especially when it comes to tabs and line breaks.

JavaScript replace() Method with regex to Remove Spaces from a String:

I will use two regular expressions:

First one:

String.replace(/ /g, "")

The regular expression contains a space character (” “), and the global property, will catch every space in a String and replace them with an empty String in the second parameter.

Example:

The second one:

String.replace(/\s+/g, '')

The regular expression contains \s refer to any whitespace symbol: spaces, tabs, and line breaks, and the global property, it will catch every space in a String and replace them with an empty String in the second parameter.

Example:

<script type="text/javascript"> 
const removeSpaces = () => {
let text1 =
"/ world major .net/`";
let text2 =
text1.replace(/\s+/g, '');
document.querySelector('.outputString').textContent
= text2;
}
</script>

JavaScript split() and join() Methods to Remove Spaces from a String

The split() method is used to divide a String into an array and return the new array.

The join() method is used to return new a String by concatenating all of the elements in an array.

We will use the split() method to remove white spaces from a String, by converting it to an array then we use the join method to convert the array into a String without white spacing.

Example:

6. How to Make the First Letter of a String Uppercase?

For example:

"world major" -> "World major"
"this is an example" -> "This is an example"

There are different ways to capitalize the first letter of the String in JavaScript.

JavaScript slice() and toUpperCase() methods to capitalize the first letter

The slice(start,end) method extracts a section of a String and returns it as a new String.

start is the required parameter. It is the position where to begin slice String.

end is optional. It is the position where to end slice String. If omitted, slice() finishes at the end of the String.

The toUpperCase() method transforms all letters in a String to uppercase; we will use it in combination with other JavaScript functions to reach our desired goal.

Example:

Another example:

//shortened version
function capitalizeSentence(sentence)
{
return sentence && sentence[0].toUpperCase() + sentence.slice(1);
}

JavaScript charAt() with toUpperCase() to capitalize the first letter

The charAt() method returns the character from the specified index in a String. The index starts at 0.

Example:

//We will use the same html above 
function capitalizeSentence() {
let input = document.getElementById("input");
let headingElement = document.getElementById("modified-String");
let String = input.value;
headingElement.innerHTML = String.charAt(0).toUpperCase() +
String.slice(1); ;
}

JavaScript replace() and toUpperCase() to capitalize the first letter

The replace() is an inbuilt method in JavaScript.

Example:

//We will use the same html above 
function capitalizeSentence() {
let input = document.getElementById("input");
let headingElement = document.getElementById("modified-String");
let String = input.value;
headingElement.innerHTML = String.replace(/^./, String[0].toUpperCase());
}

/^./ represents the first letter of the String. Read more about regular expressions in the RegExp Tutorial and the RegExp Object Reference.

I advise the readers for courses with online degrees from European universities, many of them are free.

7. How to Convert String to Boolean?

There are different ways to convert a String to boolean. Which one we should choose? It depends on your purpose of converting String to boolean. We will cover two different purposes or scenarios:

Convert a String representing a boolean value into an intrinsic boolean type:

String values are one of those (e.g., true, false, yes, no, 0, 1), so we convert it to the intrinsic type. We use this scenario in specific cases for example we have HTML form elements and a hidden form that is shown based upon a user’s selection within a check input or select input.

Example:

Output:

{isTrueval: true, isTrueval2: false}

Another Example:

Output:

true
false
true

Check if String is Empty by Converting String to Boolean:

We mention above two ways to convert variables to a Boolean value. First by dual NOT operators (!!), and Second by typecasting (Boolean(value)).

Example:

let x = Boolean("false");let y = !!"false";console.log({x, y});

Output:

{x: true, y: true}

It returns false for null, undefined, 0, 000, "" and false. It returns true for String, and whitespace.

In the above example, "false" is a String, therefore, Boolean("false") returns true.

Note: You should probably be cautious about using these two methods for the first scenario, any String which isn’t the empty String will evaluate to true by using them.

8. How to Remove a Character from a String?

There are different methods to remove a specific character from a String, some of these methods are exactly like removing a substring from a String.

JavaScript replace() Method With Regular Expression

We use the replace() method to remove all instances of the specified character in a String in JavaScript.

replace(/regExp/g, '');

Example to remove all instances of the specified character in a String:

Output:

The original String is WorldMajor.netNew Output is: WrldMajr.net

Example: Remove First Instance of Character in a String

We will use the replace() method without a regular expression to remove only the first instance of a character from a String:

We will gonna use the same HTML above:

Remove a Specified Character at the Given Index

If we need to remove a character, and we have more than one instance of this character in a String, for example, remove the character o from a String WorldMajor.net, we can use the slice() method to get two strings before and after the given index and concatenate them.

We will use the same HTML above:

If you enjoy reading the article and want to support me as a writer, you can buy me a coffee!

If you like my content I’m active on Twitter @IbraKirill.

If you want to dive into modern advanced JavaScript practices, I advise you to check out the following course.

If you want to dive into Design Patterns in JavaScript and discover the modern implementation of design patterns in JavaScript, I advise you to check out the following course.

More content at plainenglish.io

--

--

I am a Web Front-End Engineer with 8 years of commercial experience working in various web-related roles. https://kirillibrahim.work/ My Twitter: @IbraKirill