10 Awesome JavaScript String Tips You Might Not Know About
Tags: javascript, typescript, tutorial, beginners
Published: 2020-12-17 14:35:05

*This post was originally published at [kais.blog](https://kais.blog/p/10-awesome-javascript-string-tips-you-might-not-know-about).*

**Let's move your learning forward together!** [Follow me on Twitter](https://twitter.com/intent/follow?screen_name=kais_blog) for your daily dose of developer tips. Thanks for reading my content!

---

In my last post, I’ve shown you [14 Awesome JavaScript Array Tips You Should Know About](https://dev.to/kais_blog/14-awesome-javascript-array-tips-you-should-know-about-1d0m). 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**](#1-how-to-copy-a-string-multiple-times)
2. [How to **Pad** a **String** to a Specific Length](#2-how-to-pad-a-string-to-a-specific-length)
3. [How to **Split** a **String Into** an **Array of Characters**](#3-how-to-split-a-string-into-an-array-of-characters)
4. [How to **Count Characters** in a String](#4-how-to-count-characters-in-a-string)
5. [How to **Reverse Characters** in a String](#5-how-to-reverse-characters-in-a-string)
6. [How to **Capitalize (Uppercase)** the **First Letter** in a String](#6-how-to-capitalize-uppercase-the-first-letter-in-a-string)
7. [How to **Split** a String **on Multiple Separators**](#7-how-to-split-a-string-on-multiple-separators)
8. [How to **Check** If a **String Contains** a Specific Sequence](#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](#9-how-to-check-if-a-string-starts-or-ends-with-a-specific-sequence)
10. [How to **Replace All** Occurrences of a String](#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.

```ts
// 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](https://blog.npmjs.org/post/141577284765/kik-left-pad-and-npm). 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.

```ts
// 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 (`...`).

```ts
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.

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

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

```ts
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.

```ts
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*](https://www.unicode.org/reports/tr29/#Grapheme_Cluster_Boundaries). 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.

```ts
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*](https://www.unicode.org/reports/tr29/#Grapheme_Cluster_Boundaries) 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.

```ts
let word = "apple";

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

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

```ts
// 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:

```ts
// 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.

```ts
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.

```ts
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.

```ts
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!

---

**Let's move your learning forward together!** [Follow me on Twitter](https://twitter.com/intent/follow?screen_name=kais_blog) for your daily dose of developer tips. Thanks for reading my content!

*This post was originally published at [kais.blog](https://kais.blog/p/10-awesome-javascript-string-tips-you-might-not-know-about).*