javascript-tipo-string

The String Type in JavaScript

  • 2 min

In JavaScript, the String type is a basic type that allows us to handle text and perform operations with it.

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 existing ones).

Defining a 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 (`): Called Template Strings, they offer additional functionality.

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!`;
Copied!

Character escaping

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

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

Concatenating Strings

In JavaScript you can concatenate Strings using the + operator.

const name = "Luis" + " and " + "Maria"; // "Luis and Maria"
Copied!

In general, it’s 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 via the String constructor.

String.length

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

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

Methods for manipulating strings

JavaScript provides many methods for working with strings.