10 Awesome JavaScript String Tips You Might Not Know About

published

In my last post, I’ve shown you 14 Awesome JavaScript Array Tips You Should Know About. This time, let’s talk about a data type you are probably using every day.

We call a sequence of characters a string. This is one of the most basic data types you'll encounter in pretty much every programming language. Usually there's nothing fancy about it. Yet, I'd like to show you 10 awesome tips about JavaScript strings, you may not have known.

  1. How to Copy a String Multiple Times
  2. How to Pad a String to a Specific Length
  3. How to Split a String Into an Array of Characters
  4. How to Count Characters in a String
  5. How to Reverse Characters in a String
  6. How to Capitalize (Uppercase) the First Letter in a String
  7. How to Split a String on Multiple Separators
  8. How to Check If a String Contains a Specific Sequence
  9. How to Check If a String Starts or Ends With a Specific Sequence
  10. How to Replace All Occurrences of a String

1. How to Copy a String Multiple Times

JavaScript strings allow for easy repetition. Instead of duplicating a string by hand, you can make use of the String#repeat method.

// Concatenate "ha" 3 times.
const laughing = "ha".repeat(3);
console.log(laughing); // "hahaha"

// Concatenate "1" 8 times.
const eightBits = "1".repeat(8);
console.log(eightBits ); // "11111111"

2. How to Pad a String to a Specific Length

Sometimes, you want your string to have a specific length. If your string is too short, you’d like to fill the remaining space until it reaches your specific length. In the past, people often used libraries for this. This had negative consequences with the notorious left-pad incident. But, today you can use String#padStart and String#padEnd. Which method you choose depends on whether you want to pad your string at the beginning or the end.

// Add "0" to the beginning until the string has a length of 8.
const eightBits = "001".padStart(8, "0");
console.log(eightBits); // "00000001"

// Add "*" to the end until the string has a length of 5.
const anonymizedCode = "34".padEnd(5, "*");
console.log(anonymizedCode); // "34***"

3. How to Split a String Into an Array of Characters

There are multiple ways to split a string into an array of characters. I prefer using the spread-Operator (...).

const word = "apple";
const characters = [...word];
console.log(characters); // ["a", "p", "p", "l", "e"]

Note, that this does not always work as intended. See the next tip for more information.

4. How to Count Characters in a String

Easy. You can use the length property.

const word = "apple";
console.log(word.length); // 5

But, wait a minute! Sometimes, this shows some strange behavior. Look at the following example:

const word = "𩸽";
console.log(word.length); // 2

Weird! The japanese kanji hokke returns a length of 2. Why? JavaScript represents most characters as 16-bit code points. But, some characters are represented as two (or more) 16-bit code points. This is called a surrogate pair. If you are using the length property, it's not using the human-perceived length. Instead, JavaScript tells you how many code points are used. So, 𩸽 (hokke) consists of two code points. Therefore, the wrong value is returned.

Can we do something about it? Well, yes. The fellow spread-operator (...) saves our day, again.

const word = "𩸽";
const characters = [...word];
console.log(characters.length) // 1;

But, this is not the full story. It works most of the time, but there are edge cases. For example, if you are working with emoji, sometimes also this length is false. If you really want to count the human-perceived characters, then you have to split your word into grapheme clusters. Unfortunately, this is beyond the scope of this article.

5. How to Reverse Characters in a String

Reversing the characters in a string is easily done. Simply combine the spread-Operator (...), the Array#reverse method and the Array#join method.

const word = "apple";
const reversedWord = [...word].reverse().join("");
console.log(reversedWord); // "elppa"

Again, like in the previous tip there are some rare edge cases. It might be possible that you have to split your word into grapheme clusters first. Again, this is beyond the scope of this article. Sorry!

6. How to Capitalize (Uppercase) the First Letter in a String

A very common operation is capitalizing the first letter of a string. While many programming languages have a native way to do so, JavaScript needs a little work.

let word = "apple";

// Concatenate capitalized first character with remaining word.
word = word[0].toUpperCase() + word.substr(1);

console.log(word); // "Apple"
// This shows an alternative way
let word = "apple";

// Use spread operator (`...`) to split into characters.
// Transform first character and join array.
const characters = [...word];
characters[0] = characters[0].toUpperCase();
word = characters.join("");

console.log(word); // "Apple"

Remember, what we perceive as characters might be different to what JavaScript perceives as a character. Look at #4 for an explanation.

7. How to Split a String on Multiple Separators

Let's say you want to split a string on a separator. Therefore, you can use the String#split method. You probably know this. However, did you know you could split on multiple separators at the same time? This is possible using a regular expression:

// Let's split on comma (,) and semicolon (;).
const list = "apples,bananas;cherries"
const fruits = list.split(/[,;]/);
console.log(fruits); // ["apples", "bananas", "cherries"]

8. How to Check If a String Contains a Specific Sequence

Searching in strings is a common task. In JavaScript you can do this very easily with the String#includes method. No regular expression needed.

const text = "Hello, world! My name is Kai!"
console.log(text.includes("Kai")); // true

9. How to Check If a String Starts or Ends With a Specific Sequence

Similar to #8, you can search at the beginning or the end of a string. For this you can use the String#startsWith and String#endsWith methods.

const text = "Hello, world! My name is Kai!"

console.log(text.startsWith("Hello")); // true

console.log(text.endsWith("world")); // false

10. How to Replace All Occurrences of a String

There are multiple ways for replacing all occurrences of a string. You can either use the String#replace method and a regular expression with the global flag. Or, you could use the new String#replaceAll method. Note that this new method is not yet available in every browser and Node.js version.

const text = "I like apples. You like apples."

console.log(text.replace(/apples/g, "bananas"));
// "I like bananas. You like bananas."

console.log(text.replaceAll("apples", "bananas"));
// "I like bananas. You like bananas."

Conclusion

String is one of the most basic data type in almost every programming language. Also, it's one of the very first data types new developers are learning about. Yet, especially in JavaScript, many developers don't know some interesting details about strings. Hopefully, my post was interesting for you! I'll try to update it with new tips in the future.

Thanks a lot for reading this post. Please consider sharing it with your friends and colleagues. See you soon!


You May Also Be Interested in the Following Posts