JS String

JavaScript Strings

In JavaScript, strings are used to store and manipulate text. A string is a sequence of characters like letters, numbers, and symbols, all wrapped inside quotation marks.

How to Create a String in JavaScript

There are three ways to create a string in JavaScript:

1. Using Single Quotes (‘ ‘)
2. Using Double Quotes (” “)
3. Using Backticks (Template Literals ` `)

Example

let name1 = ‘John’; // Single quotes
let name2 = “John”; // Double quotes
let name3 = `John`; // Template literal (introduced in ES6)

console.log(name1);
console.log(name2);
console.log(name3);

Output
Js-String

In JavaScript, single quotes and double quotes are treated the same, so you can use either. However, template literals (backticks) allow you to create multiline strings and embed expressions easily.

Note:

When using backticks (template literals), you can include variables and expressions inside your strings.

Example with Template Literals

let age = 16;
let message = `John is ${age} years old`; // Embedding a variable inside a string
console.log(message); // Output: John is 16 years old

Output
Js-Template-

In this line, let message = `John is ${age} years old`; a template literal is used (with backticks ). Inside this string, ${age} is a placeholder that allows the value of the variable age to be embedded directly into the string. So, it will automatically replace ${age} with the value of the variable age, which is 16.

Including Quotes Inside a String

If you want to include quotes inside a string, make sure they don’t match the surrounding quotes. If they do, you’ll need to use escape characters.

Example

let sentence1 = “He said, ‘JavaScript is awesome!'”; // Single quotes inside double quotes
let sentence2 = ‘She replied, “Yes, it is!”‘; // Double quotes inside single quotes

console.log(sentence1);
console.log(sentence2);

Output
Js-Quets
In this example

•  sentence1 uses double quotes (” “) as the outer quotes and includes a single quote (‘ ‘) inside the string. This is allowed because the inner single quote does not conflict           with the outer double quotes.
  sentence2 uses single quotes (‘ ‘) as the outer quotes and includes double quotes (” “) inside the string. Similarly, this is valid since the inner double quotes do not conflict         with the outer single quotes.

Escape Characters

An escape character is a backslash (\) that allows you to include special characters in a string. For example, you can use a backslash to insert single or double quotes without breaking your code.

Escape Code Character Description
\’ Single quote (‘) Inserts a single quote inside a string that uses single quotes.
\” Double quote (“) Inserts a double quote inside a string that uses double quotes.
\\ Backslash (\) Inserts a backslash inside a string.
Example

let str1 = ‘It\’s a beautiful day!’;
let str2 = “She said, \”JavaScript is fun!\””;
let str3 = “This is a backslash: \\”;

document.write(str1 + ‘<br>’);
document.write(str2 + ‘<br>’);
document.write(str3);

Output
Js-Scap
In this example

•  let str1 = ‘It\’s a beautiful day!’; : The single quote in “It’s” is escaped with a backslash (\’) so that it doesn’t end the string prematurely. The string can be read as: “It’s a             beautiful day!”
  let str2 = “She said, \”JavaScript is fun!\””; : The double quotes around “JavaScript is fun!” are escaped with a backslash (\”) to include them within the string. The output      will be: She said, “JavaScript is fun!”
•  let str3 = “This is a backslash: \\”;: The backslash itself is escaped with another backslash (\\) so that it can be displayed in the output. The output will be: This is a                   backslash: \

String Length

You can find out how many characters a string has by using the .length property.

Example

let myText = “Hello, World!”;
console.log(myText.length); // Output: 13

Output
Js-String-O-output

In this example, the length of the string “Hello, World!” is 13, because it counts every character, including spaces and punctuation.

String Concatenation

String concatenation means joining two or more strings together. In JavaScript, you can use the + operator to do this.

Example

let firstName = “John”;
let lastName = “Doe”;
let fullName = firstName + ” ” + lastName; // Joining the two strings with a space
console.log(fullName); // Output: John Doe

Output
In this example

•   In this line, let fullName = firstName + ” ” + lastName; you create a new variable called fullName. You combine (concatenate) the firstName and lastName variables.
   The + operator is used to join strings. In this case, you also add a space between them by using ” “. So, it becomes “John Doe”.

Multiline Strings (Template Literals)

With template literals (backticks), you can create multiline strings easily, keeping the format as it is.

Example

let poem = `
Roses are red,
Violets are blue,
JavaScript is cool,
And so are you!
`;
console.log(poem);

Output
Js-Multiline-String

The backticks (“) are used to define the string, allowing it to span multiple lines without needing any special escape characters.

String Comparison

When comparing two strings, JavaScript uses:

•  == to check if two values are equal
•  === to check if two values and their types are both equal

Example

let x = “John”;
let y = new String(“John”);

console.log(x == y); // Output: true (same value)
console.log(x === y); // Output: false (different types)

Output

In this case, x is a string literal and y is a string object. Even though their values are the same, their types are different.

Avoid Using the new Keyword

It is recommended not to use the new keyword to create strings because it makes your code more complex and slower. Instead, stick to string literals like this:

let myString = “Hello!”;

Conclusion

JavaScript strings are essential for working with text. You can create strings using single, double quotes, or backticks, perform operations like concatenation, find the string length, and even include special characters using escape sequences. Stick with string literals for simplicity and better performance.

Course Video

YouTube Reference:

Practice Scenarios

Scenario 1: String Creation and Manipulation

Objective: Create different types of strings using single quotes, double quotes, and template literals. Then, manipulate these strings to demonstrate string concatenation and length calculation.
Expected Output: A console output showing the created strings, their concatenated result, and the length of each string.

Code Example:

// Create strings using different methods
let singleQuoteString = ‘Hello, World!’; // Single quotes
let doubleQuoteString = “Learning JavaScript is fun!”; // Double quotes
let name = “Alice”;
let templateLiteralString = `Welcome, ${name}!`; // Template literal

// Concatenate strings
let combinedString = singleQuoteString + ” ” + doubleQuoteString;

// Calculate lengths
let length1 = singleQuoteString.length;
let length2 = doubleQuoteString.length;
let length3 = templateLiteralString.length;
let lengthCombined = combinedString.length;

// Output results
console.log(singleQuoteString); // Output: Hello, World!
console.log(doubleQuoteString); // Output: Learning JavaScript is fun!
console.log(templateLiteralString); // Output: Welcome, Alice!
console.log(combinedString); // Output: Hello, World! Learning JavaScript is fun!
console.log(`Length of singleQuoteString: ${length1}`); // Output: Length of singleQuoteString: 13
console.log(`Length of doubleQuoteString: ${length2}`); // Output: Length of doubleQuoteString: 29
console.log(`Length of templateLiteralString: ${length3}`); // Output: Length of templateLiteralString: 15
console.log(`Length of combinedString: ${lengthCombined}`); // Output: Length of combinedString: 43

Output

Scenario 2: Using Escape Characters

Objective: Demonstrate how to include special characters in strings using escape characters.
Expected Output: A console output showing strings that include single quotes, double quotes, and a backslash.

Output
Js-Using-Escape

Scenario 3: Multiline String Creation

Objective: Use template literals to create a multiline string that contains a short poem or a message.
Expected Output: A console output displaying the multiline string correctly formatted.

Output
Js-Multiline-String-

Scenario 4: String Initialization

Objective: Demonstrate how to initialize strings using various quotation marks.
Expected Output: A console output showing different ways to create strings.

Output

Scenario 5: String Concatenation

Objective: Create two separate strings and concatenate them into one.
Expected Output: A console output showing the concatenated string

Output

Scenario 6: String Length Calculation

Objective: Create a string and calculate its length.
Expected Output: A console output showing the original string and its length.

Output

Scenario 7: Using Template Literals for Dynamic Strings

Objective: Create a dynamic greeting message using template literals.
Expected Output: A console output displaying a personalized greeting message.

Output

Scenario 8: Combining Strings and Variables

Objective: Combine strings with variables to create a sentence.
Expected Output: A console output showing the complete sentence formed by combining strings and variables.

Output

Scenario 9: Escape Sequences in Strings

Objective: Create strings that include escape sequences for special characters.
Expected Output: A console output demonstrating the use of escape sequences.

Output
JS-Scape-

Scenario 10: String Variables and Constant Strings

Objective: Create a constant string and a variable string, then output them.
Expected Output: A console output showing both the constant and variable strings.

Output

Scenario 11: Basic Template Literal Usage

Objective: Create a sentence using a template literal.
Expected Output: A console output showing the complete sentence using template literals.
1-   name: John
2-   hobby: painting

Output
JS-Basic-Template

Scenario 12: Template Literals with Expressions

Objective: Use expressions within a template literal to calculate and display a result.

Expected Output: A console output showing the result of the expression embedded in the template literal.

1.   base = 5; height = 10;
2.   Formula area of a triangle = 0.5 * base * height

Output

Scenario 13: Nesting Template Literals

Objective: Demonstrate nesting template literals within each other.
Expected Output: A console output showing the result of the nested template literals.
Name: Alice

Output
JS-Nesting

Scenario 14: Using Template Literals for HTML Strings

Objective: Create a simple HTML structure using template literals.
Expected Output: A console output showing a string that contains HTML.

Code Example

// Define variables for a title and content
let title = “Welcome!”;
let content = “This is a simple template literal example.”;

// Create an HTML string using template literals
let htmlString = `<h1>${title}</h1>
<p>${content}</p>`;

// Output the HTML string
document.write(htmlString);

Output
JS-Using-LIterals

Scenario 15: Creating a Dynamic URL with Template Literals

Objective: Construct a dynamic URL using template literals based on user input.
Expected Output: A console output showing the constructed URL.

1-  baseURL = “https://example.com/user/”;
2-  userID = 42;

Output
JS-Creating-a-Dynamic
Frequently Asked Questions

Still have a question?

Let's talk

A string in JavaScript is a sequence of characters used to represent text. Strings are enclosed in single (‘), double (“), or backticks (`).

You can create a string using:

  • Single quotes: ‘Hello’
  • Double quotes: “Hello”
  • Template literals: `Hello` (introduced in ES6).

Template literals are strings enclosed in backticks (`) that support embedded expressions and multi-line strings. Example:

let name = “John”; 

console.log(`Hello, ${name}!`);

Use the .length property to determine the number of characters in a string. Example:

let text = “Hello”; 

console.log(text.length); // Output: 5

Yes, you can include special characters like quotes, newlines, or tabs using escape sequences. Example:

let text = “This is a \”quoted\” word.”;

Use the + operator or template literals to combine strings. Example:

let firstName = “John”; 

let lastName = “Doe”; 

console.log(firstName + ” ” + lastName); // Output: John Doe

Use template literals for multi-line strings. Example:

let text = `This is a multi-line string

that spans multiple lines.`;

  • == compares values after type coercion.
  • === compares values and types strictly. For strings, it’s recommended to use ===.

No, strings are immutable in JavaScript. You cannot change the string itself, but you can create a new string with the desired changes.

Some commonly used string methods include:

  • .toUpperCase() and .toLowerCase()
  • .slice()
  • .substring()
  • .replace()
  • .split()

 

let greeting = “Hello, World!”; 

let name = ‘John Doe’; 

let message = `Welcome, ${name}!`; 

For more examples and details, check out our JavaScript string examples tutorial.

Yes, we offer a JavaScript string free course video, which covers string creation, manipulation, and common operations in JavaScript.

We provide a Learn JavaScript string methods with free video tutorial that explains how to use various string methods such as toUpperCase(), slice(), replace(), and more.

We offer a Free tutorial on JavaScript strings for beginners, where you’ll learn everything from string creation to advanced string manipulation techniques in JavaScript.

String properties in JavaScript are attributes that provide information about a string. Example: .length gives the length of the string.

String functions in JavaScript are predefined methods that provide functionality to transform, search, or analyze string values, enabling easy text manipulation.

${} is used in template literals to embed expressions inside strings. It allows variables or calculations to be directly inserted into a string. Example: `Hello, ${name}!`

The most common property is .length, which returns the number of characters in the string. JavaScript strings are also immutable, meaning their properties cannot be changed.

Functions in strings refer to methods that allow operations on string data, such as .concat(), .includes(), .charAt(), .substring(), .slice(), .trim().