A Brief Look at JavaScript String

A Brief Look at JavaScript String

Do you know String is an indispensable data type in your code? Well, evidently, since the web is mostly text-based and Strings are texts. Interestingly, JavaScript has enough features for manipulating Strings. Read on, to take a walk in the park of JavaScript String briefly :).

I am presenting a short article for anyone looking for a quick guide or refresher on JavaScript String; it covers few of the basics and some of the helpful operations that we can perform on Strings with built-in methods.

The Basics

Strings are created by declaring a variable and assigning a text value to the variable.

create string

In the code snippet above, variable foo and bar were declared and assigned some friendly text. However, you will notice that one have single quotes around it while the other has double quotes — that is because, in JavaScript, you create Strings by putting your text inside any of the two.

A bad String creation will look like this:

bad string

Can you spot what is wrong? The first String used only one quote and the second mixed single quotes and double-quotes.

If your text has ' then, you can escape the quote — that is, make the quote mark a text and not code syntax. See an illustration below:

escape character

Above, I used the \ escape character; others include \\, \". See here for a list of escape characters.

Some of the Important String Operations

  • Joining Strings: descriptive enough, right? — the elegant word, for joining one or more Strings together, is Concatenation. We can concatenate Strings using two methods; template literals and add + operator.
let name = 'Kafee';

let greetingsUsingTemplateLiteral = `Bonjour ${name}`;   // Bonjour Kafee
let greetingsUsingAddOperator = 'Bonjour ' + name;   // Bonjour Kafee
  • Finding the length of a String: are you writing a super cool algorithm and you need the size of a String? Do not worry; JavaScript has your back! :)
let foo = 'Polar bear';

let fooLength = foo.length;   // 10

Note: JavaScript engine counts white spaces as characters.

  • Retrieving a character in a String: You can get a character in a String using the [] notation.
let foo = 'Polar bear';

foo[1];    // o
  • Capitalizing a String: this is done using the toUpperCase() method on the String.
let foo = 'bar';

foo.toUpperCase();     //  Bar
  • Replace a part of a String using the replace() in-built method. It takes two parameters, the String you want to replace, and the String you want to replace it with
let foo = 'Polar bear';

foo.replace('Polar', 'Cute');     // Cute bear

See w3schools for a complete list of in-built methods of JavaScript String.