Strings in JavaScript: What they are and how to use them

by Janeth Kent Date: 22-06-2021 javascript

In this tutorial we are going to explain what strings are and how they are used in JavaScript. The tutorial is intended for people who are learning to program in JavaScript. You will learn how to create strings, how to display the content of strings, how to concatenate strings and how to store strings in variables. We will also see all the types of syntax used to declare them.


What is a string


A string is a primitive data type consisting of a sequence of characters. These characters can be letters, numbers or symbols. Strings are immutable, so they do not change over time.

Strings are used to display or modify text, and these operations are fundamental to almost every programming language. It is important not to confuse them with variables, since a string is the data you can assign to a variable and not the variable itself, hence its immutability.


How to create a string


In JavaScript there are three methods by which you can create a string. You can create them inside single quotes, as in `this text`, inside double quotes, as in `this other text` and finally using inverted quotes, as in `this text`. The inverted commas you use to start the string and to close it must be of the same type, although you can create strings using all types of inverted commas in the same script.

Strings using single quotes and double quotes work the same way. There is no official convention about which type of inverted commas to use, although single inverted commas are usually used whenever possible, and double inverted commas are usually reserved for HTML attributes if you also use this other language. But the most important thing is that you are consistent in their use:

// Single inverted commas  
'This text is enclosed in single inverted commas.'    
// Double quotes  
"This other text is enclosed in double quotes."

Unlike the two previous cases, strings declared with inverted commas work in a different way and are called template literals. The basic operation of template literals is identical to that of strings declared with single or double quotes:

`This text is declared as a template literal.`

However, literal templates have many more possibilities when defining and working with strings. In this article we will look at some of the most relevant ones.

Strings declared in code are also called literals of a string, and include the symbols with which they are declared. For example, a string of any type declared in the code, whether declared with single, double or inverted quotes, would be a literal:

'This is a text'

On the other hand, the value of the string literal above would be the text itself:

This is a text

A string literal corresponds to the string as it is displayed in the code, including the quotes used to define it. On the other hand, the value of a string is the value that would be displayed on the screen if it were displayed, without JavaScript's own inverted commas and symbols.


How to display a string

The simplest method by which you can display a string on screen with JavaScript is to display it on the console using the console.log() method, as you see in this example:

console.log('This string will be displayed by the console');

Another very simple method is to use the alert() function, available in all browsers:

alert('This is a string');;

When executing the above function, the browser will display a message with the string.

When you want to test or debug the code, the most common is to use the console.log() method, because when you use the alert() function, you will have to close each and every message that is displayed.


How to assign strings to variables


Variables in JavaScript are defined using the var or let statements, although you can also define constants using the const statement. In the following example we assign a string to a constant, to a variable declared with let and to another variable declared with var:

const string = 'This string is assigned to a constant;
let varString1 = 'This string is assigned to a variable.';
let varString2= 'This string is assigned to another variable.';

Once you have assigned the string to a constant or variable, you can display it in the console by passing the desired constant or variable to the console.log() method:


Thanks to the use of variables, we can store and manipulate strings easily, avoiding also having to write them every time we are going to use them.


Types of strings in JavaScript


In JavaScript there are two types of strings, which are primitive strings and those that are String objects. Primitive strings are the ones we have seen in the previous sections.

To see the difference between the two types of strings, we are going to initialise a primitive string and an object string:

// String of primitive type
const primitiveString = 'String of primitive type;
// String of type object
const stringObject = new String('String of type object.');

To determine the type of a string you can use the typeof operator. For example, if you run the code typeof stringPrimitive, you will get string as a result:

const typeString = typeof stringPrimitive;
console.log(typeString); // string

If you execute the code typeof stringObject instead, you will get object as a result:

const typeString = typeof stringObject;
console.log(typeString); // object

However, the most common way to work with JavaScript is with primitive strings. In addition, JavaScript is able to use the methods and properties included in String objects even if you use primitive strings, without you having to perform any kind of conversion.

In general, whenever you access a property or execute a method of a String on a primitive string, JavaScript will perform a temporary conversion of the string to a String object, execute the method and return the result.


Indexing strings


The characters of a string in JavaScript are indexed with an index starting with the number 0. The index is incremented by one with each character added to the string.

For example, let's see how the string Hello! is indexed internally:



The characters are ordered in order starting at index 0, which corresponds to the letter H. The index is incremented until the string ends with the value ! The index is incremented until the string ends with the value !, which is at position 4. Whitespace also counts as a fully normal character.

You can access an individual character in a string in the same way as you would an array. In the following example, we access the character at position 3, which corresponds to the letter d, since we start counting from the number 0:

const character = 'Good morning'[3]; // d

Alternatively, you can use the charAt method, which will return the character at the position you specify as a parameter:

const character = 'Good morning'.charAt(3); // d

If instead you want to know the position of a certain character, you can use the indexOf method. The indexOf method will return the first occurrence of the character you pass to the method as a parameter:

const position = 'Good morning'.indexOf('d'); // 3

In addition, using the indexOf method you can not only find individual characters, but you can also find the position where the first occurrence of the substring you pass as a parameter begins:

const position = 'Good morning''.indexOf('morning'); // 5

If the character or substring is not found, the result of the indexOf method will be -1.

In case instead of getting the first occurrence you want to get the last occurrence, you must use the lastIndexOf method:

const position = 'Good morning'.lastIndexOf('g'); // 11

The lastIndexOf method can also be used to find the position where the last occurrence of a substring begins. If the character or substring is not found, the lastIndexOf method shall return -1.


Length of strings


You can get the length of a string at any time by using the length property, which will return the number of characters in a string.

"It's time to kick ass".length // 21

It is important to remember that the length property will return the length of the string, starting with the number 1. It will not return the last index, which in the case of the above string will be the value 20, as indexes start with the value 0.


How to escape characters


To escape characters in a string you will have to use the symbol immediately before the character you want to escape. This will allow you, among other things, to include single quotes inside a string declared with single quotes:

const mystring = 'I'm the king of the hill';    

Concatenation of strings


You can join two or more strings together using the + operator as you can see in this example:

const mystring = 'Yesterday I ate ' + 'apples'; // Yesterday I ate apples

You can also use the += operator to append a string to the end of another string:

let cadena = 'Yesterday I ate ';  
cadena += 'apples';  
//  Yesterday I ate apples

As we will see in the next section, you can also use the concat() method to join strings.

const firstName = 'Eduardo';
const surname = ' Lázaro';
const completeName = firstName.concat(surname); // Eduardo Lázaro

In addition, in case you use literal templates, you can also include variables inside strings thanks to the ${} syntax:

const Myobject = 'book';  
const preferred = 'Don Quijote';    
const favourite = `My favourite ${Myobject} is ${preferred}.`;

Multi-line strings


In JavaScript you can create strings that take up multiple lines, both in the code and in the result that will be displayed on the screen. To start a new line, simply use the syntax. In case you are going to display the text in an HTML document, you can create a new line using the <br> tag, or you can start a new paragraph using the <p> tag and close it using </p>.

However, sometimes we will have to write strings that are too long in the code, resulting in unreadable code. To solve this, we can concatenate several strings or use the character set, although the latter method is not very compatible with browsers. The best option is to use template literals:

const stringMultiline = `First line and
second line;

String transformations


In JavaScript you can apply different transformations to strings. For example, you can transform their characters to uppercase or lowercase using the toUpperCase or toLowerCase methods:

const Mystring = 'this is a string';
const stringMayusc = Mystring.toUpperCase(); // THIS IS A STRING


Methods used with strings


Below you can find a list of the most commonly used methods with strings in JavaScript:

charAt method

charCodeAt method

codePointAt method

startsWith method


And that's it. With this guide we have covered everything you should know about strings and their manipulation with JavaScript. You have learned how to create strings with a different syntax and also how to create literal templates.

by Janeth Kent Date: 22-06-2021 javascript hits : 7549  
Janeth Kent

Janeth Kent

Licenciada en Bellas Artes y programadora por pasión. Cuando tengo un rato retoco fotos, edito vídeos y diseño cosas. El resto del tiempo escribo en MA-NO WEB DESIGN AND DEVELOPMENT.


Related Posts

How to use the endsWith method in JavaScript

In this short tutorial, we are going to see what the endsWith method, introduced in JavaScript ES6, is and how it is used with strings in JavaScript. The endsWith method is…

What are javascript symbols and how can they help you?

Symbols are a new primitive value introduced by ES6. Their purpose is to provide us unique identifiers. In this article, we tell you how they work, in which way they…

Callbacks in JavaScript

Callback functions are the same old JavaScript functions. They have no special syntax, as they are simply functions that are passed as an argument to another function. The function that receives…

How to create PDF with JavaScript and jsPDF

Creating dynamic PDF files directly in the browser is possible thanks to the jsPDF JavaScript library. In the last part of this article we have prepared a practical tutorial where I…

How to make your own custom cursor for your website

When I started browsing different and original websites to learn from them, one of the first things that caught my attention was that some of them had their own cursors,…

Node.js and npm: introductory tutorial

In this tutorial we will see how to install and use both Node.js and the npm package manager. In addition, we will also create a small sample application. If you…

How to connect to MySQL with Node.js

Let's see how you can connect to a MySQL database using Node.js, the popular JavaScript runtime environment. Before we start, it is important to note that you must have Node.js installed…

JavaScript Programming Styles: Best Practices

When programming with JavaScript there are certain conventions that you should apply, especially when working in a team environment. In fact, it is common to have meetings to discuss standards…

Difference between arrow and normal functions in JavaScript

In this tutorial we are going to see how arrow functions differ from normal JavaScript functions. We will also see when you should use one and when you should use…

JavaScript Arrow functions: What they are and how to use them

In this article we are going to see what they are and how to use JavaScript Arrow Functions, a new feature introduced with the ES6 standard (ECMAScript 6). What are Arrow…

How to insert an element into an array with JavaScript

In this brief tutorial you will learn how to insert one or more elements into an array with JavaScript. For this we will use the splice function. The splice function will not…

What is the difference between primitives types and objects in JavaScript?

In this short tutorial we are going to look at the differences between primitive types and objects in JavaScript. To start with, we're going to look at what primitive types…

We use our own and third-party cookies to improve our services, compile statistical information and analyze your browsing habits. This allows us to personalize the content we offer and to show you advertisements related to your preferences. By clicking "Accept all" you agree to the storage of cookies on your device to improve website navigation, analyse traffic and assist our marketing activities. You can also select "System Cookies Only" to accept only the cookies required for the website to function, or you can select the cookies you wish to activate by clicking on "settings".

Accept All Only sistem cookies Configuration