Language: EN

javascript-tipo-string

The String Type in JavaScript

In JavaScript, the type String is a basic type that allows us to handle texts and perform operations on them.

A String (or character string) is a sequence of Unicode characters that can include letters, numbers, symbols, and spaces.

In JavaScript, strings are immutable. This means that once created, they cannot be modified (however, we can create new strings from the existing ones).

Definition of string

A String in JavaScript can be defined using single quotes, double quotes, or backticks.

  • Single quotes ('): Commonly used to define simple character strings
  • Double quotes ("): Equivalent to single quotes
  • Backticks (`): Known as Template Strings, and offer additional functionalities

For example, all these ways of creating a String are valid

// Using single quotes
const message1 = 'Hello, world!';

// Using double quotes
const message2 = "Hello, world!";

// Using backticks (template literals)
const message3 = `Hello, world!`;

Escape characters

If you need to include quotes within a string, you must escape them using the backslash (\).

const text = "She said: \"Hello!\"";

Manipulating strings

Concatenating Strings

In JavaScript, you can concatenate Strings using the + operator

const name = "John" + " and " + "Maria"; // "John and Maria"

In general, it is better to use Template literals because they are more readable.

Properties of the String Object

Although Strings in JavaScript are primitives, they can be used as objects through the String constructor. This provides access to several useful properties:

String.length

The length property returns the number of characters in a string.

let text = 'JavaScript';
console.log(text.length); // 10

Methods to manipulate strings

JavaScript provides many methods to work with strings.