In JavaScript, the type String is a basic type that allows us to handle text and perform operations on 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).
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!`;
Template literals allow for variable and expression interpolation, making it easier to create dynamic strings.
We see it in the entry
Escape characters
If you need to include quotes within a string, you must escape them using the backslash (\
).
const text = "She said: \"Hello!\"";
String manipulation
Concatenating Strings
In JavaScript, you can concatenate Strings using the +
operator
const name = "Luis" + " and " + "Maria"; // "Luis and Maria"
In general, it is better to use a Template literal, 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.
We see it in the entry