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 : 8416  
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 upload files to the server using JavaScript

In this tutorial we are going to see how you can upload files to a server using Node.js using JavaScript, which is very common. For example, you might want to…

How to combine multiple objects in JavaScript

In JavaScript you can merge multiple objects in a variety of ways. The most commonly used methods are the spread operator ... and the Object.assign() function.   How to copy objects with…

The Payment Request API: Revolutionizing Online Payments (Part 2)

In the first part of this series, we explored the fundamentals of the Payment Request API and how it simplifies the payment experience. Now, let's delve deeper into advanced features…

The Payment Request API: Revolutionizing Online Payments (Part 1)

The Payment Request API has emerged as the new standard for online payments, transforming the way transactions are conducted on the internet. In this two-part series, we will delve into…

Let's create a Color Picker from scratch with HTML5 Canvas, Javascript and CSS3

HTML5 Canvas is a technology that allows developers to generate real-time graphics and animations using JavaScript. It provides a blank canvas on which graphical elements, such as lines, shapes, images…

How do you stop JavaScript execution for a while: sleep()

A sleep()function is a function that allows you to stop the execution of code for a certain amount of time. Using a function similar to this can be interesting for…

Mastering array sorting in JavaScript: a guide to the sort() function

In this article, I will explain the usage and potential of the sort() function in JavaScript.   What does the sort() function do?   The sort() function allows you to sort the elements of…

Infinite scrolling with native JavaScript using the Fetch API

I have long wanted to talk about how infinite scroll functionality can be implemented in a list of items that might be on any Web page. Infinite scroll is a technique…

Sorting elements with SortableJS and storing them in localStorage

SortableJS is a JavaScript extension that you will be able to use in your developments to offer your users the possibility to drag and drop elements in order to change…

What is a JWT token and how does it work?

JWT tokens are a standard used to create application access tokens, enabling user authentication in web applications. Specifically, it follows the RFC 7519 standard. What is a JWT token A JWT token…

Template Literals in JavaScript

Template literals, also known as template literals, appeared in JavaScript in its ES6 version, providing a new method of declaring strings using inverted quotes, offering several new and improved possibilities. About…

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…