DEV Community

Cover image for 10 Awesome JavaScript String Tips You Might Not Know About
Kai
Kai

Posted on • Updated on • Originally published at kais.blog

10 Awesome JavaScript String Tips You Might Not Know About

This post was originally published at kais.blog.

Let's move your learning forward together! Follow me on Twitter 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. 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"
Enter fullscreen mode Exit fullscreen mode

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***"
Enter fullscreen mode Exit fullscreen mode

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"]
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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

const word = "𩸽";
console.log(word.length); // 2
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

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"
Enter fullscreen mode Exit fullscreen mode

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"
Enter fullscreen mode Exit fullscreen mode
// 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"
Enter fullscreen mode Exit fullscreen mode

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"]
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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."
Enter fullscreen mode Exit fullscreen mode

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 for your daily dose of developer tips. Thanks for reading my content!

This post was originally published at kais.blog.

Top comments (12)

Collapse
 
fullstackcodr profile image
fullstackcodr • Edited

I like this post although a struggle I had recently was that padStart and padEnd are not supported on IE.

I tried to find polyfill but there is not an official one so I ended up in a custom solution.

Collapse
 
kais_blog profile image
Kai • Edited

Thanks! Yeah, those quirks with different browsers... MDN references this polyfill for String#padStart and String#padEnd: github.com/behnammodi/polyfill/blo...

Collapse
 
beytek profile image
Karim Sabbagh

Back when IE mattered

Collapse
 
nditanaka profile image
Tanaka

Thanks for the great post! Is there a way to easily unstringify text with a JavaScript? A kind of opposite of the stringify function? eg. how to remove the quotation marks in a dictionary of key-value pairs like {"name":"Tim", "age": "22"}. In this case, removing them just from the age value?

Thanks for the great article again!

Collapse
 
kamcio profile image
kamcio

So you basically just want to convert string to a number?

const string = '22'
const stringToNumber = +string

console.log(stringToNumber)
// 22
Enter fullscreen mode Exit fullscreen mode
Collapse
 
jdoe profile image
John Doe

Why does this work like this do you know?

Thread Thread
 
khuongduybui profile image
Duy K. Bui

Because + operator tells JavaScript to wrap both sides of it with Number(). Left side here is blank, so Number() gives you 0. Right side here is "22", so Number("22") gives you 22. Then + operator adds these 2 Numbers together and gives you 22.

That's a lazy way to convert a String to a Number.
The explicit equivalent way is const stringToNumber = Number(string).

However, if you need more fine-tuned control over the parsing of the string, consider using parseInt or parseFloat (which lets you parse number representation in bin, oct, hex, etc., not just dec)

Collapse
 
machineno15 profile image
Tanvir Shaikh • Edited

For point 6.
whats the difference between
word.substr(1) vs word.splice(1) ?

Collapse
 
kais_blog profile image
Kai

Note, splice is used for modifying arrays. I think you mean slice.

At first glance, there is no difference between word.substr(1) and word.slice(1). Both return a substring of word. However, their signature differs. The second parameter to substr is length. So, using substr(1, 5) means, take 5 characters starting at 1. In contrast, slice(1, 5) means take the characters between index 1 (inclusive) and index 5 (exclusive).

Besides, there's also a substring method. This behaves pretty much like slice. It takes a starting index and an optional ending index.

All three methods are valid ways to extract a substring. They may differ a bit in performance. Yet, the difference is more or less negligible. Choose what you find adequate.

Collapse
 
machineno15 profile image
Tanvir Shaikh

Got it, Thanks Kai it's very helpful

Collapse
 
qq449245884 profile image
qq449245884

Hello, may I translate your article into Chinese?I would like to share it with more developers in China. I will give the original author and original source.

Collapse
 
kais_blog profile image
Kai

Sure! I hope it's helpful for some developers in China :)