Strings

JavaScript Strings

Table of Contents

  1. Introduction to Strings in JavaScript

  2. Creating Strings in JavaScript

    • Using Double Quotes

    • Using Single Quotes

    • Using Backticks (Template Literals)

  3. String Properties and Methods

    • String Length

    • Changing Case

      • toUpperCase()

      • toLowerCase()

    • Extracting Parts of a String

      • slice()

      • substring()

      • substr()

    • Replacing Text in a String

    • Concatenating Strings

      • Using + Operator

      • Using concat()

    • Trimming Spaces

    • Checking for Substrings

      • includes()

      • startsWith()

      • endsWith()

  4. String Manipulation

    • Splitting Strings

    • Joining Strings

    • Repeating Strings

    • Padding Strings

  5. Special Characters in Strings

    • Escape Characters

    • Newlines

    • Tab Characters

  6. String Immutability

  7. Template Literals and String Interpolation

  8. String Comparisons

  9. Working with Multi-line Strings

  10. Conclusion


1. Introduction to Strings in JavaScript

Welcome to the Codes with Pankaj tutorial on JavaScript Strings! In this tutorial, we will explore strings in JavaScript in a simple and easy-to-understand way. By the end of this tutorial, you will have a strong understanding of how strings work in JavaScript and how to use them in your code. Let’s get started!

Strings in JavaScript are used to represent and manipulate text. They are a sequence of characters enclosed within quotes, such as "Hello", 'World', or `JavaScript`.

2. Creating Strings in JavaScript

In JavaScript, there are three ways to create strings:

Using Double Quotes

let message = "Hello, World!";

This is the most common way to define strings. Anything between the double quotes is considered part of the string.

Using Single Quotes

let greeting = 'Hi there!';

Single quotes work the same as double quotes. The choice between them often comes down to personal preference.

Using Backticks (Template Literals)

let name = `Pankaj`;

Backticks allow you to create template literals, which are special strings that can span multiple lines and include embedded expressions.

3. String Properties and Methods

String Length

To find out how many characters are in a string, use the .length property.

let text = "Codes with Pankaj";
console.log(text.length); // Output: 16

Changing Case

toUpperCase()

Converts all characters in a string to uppercase.

let lowerCaseText = "codes with pankaj";
console.log(lowerCaseText.toUpperCase()); // Output: CODES WITH PANKAJ

toLowerCase()

Converts all characters in a string to lowercase.

let upperCaseText = "CODES WITH PANKAJ";
console.log(upperCaseText.toLowerCase()); // Output: codes with pankaj

Extracting Parts of a String

slice()

Extracts a section of a string and returns it as a new string.

let sentence = "Welcome to Codes with Pankaj";
let part = sentence.slice(11, 24);
console.log(part); // Output: Codes with Pankaj

substring()

Similar to .slice(), but does not accept negative indexes.

let part2 = sentence.substring(11, 24);
console.log(part2); // Output: Codes with Pankaj

substr()

Extracts a part of the string based on the start position and length of the substring.

let part3 = sentence.substr(11, 13);
console.log(part3); // Output: Codes with Pa

Replacing Text in a String

Use .replace() to replace part of a string with another string.

let sentence = "Welcome to Codes with Pankaj";
let newSentence = sentence.replace("Pankaj", "JavaScript");
console.log(newSentence); // Output: Welcome to Codes with JavaScript

Concatenating Strings

Using + Operator

let firstPart = "Hello";
let secondPart = "World!";
let fullMessage = firstPart + ", " + secondPart;
console.log(fullMessage); // Output: Hello, World!

Using concat()

let text1 = "Hello";
let text2 = "World";
let result = text1.concat(" ", text2);
console.log(result); // Output: Hello World

Trimming Spaces

Use .trim() to remove whitespace from both ends of a string.

let spacedText = "   Hello, World!   ";
console.log(spacedText.trim()); // Output: Hello, World!

Checking for Substrings

includes()

Checks if a string contains a specified value.

let sentence = "Welcome to Codes with Pankaj";
console.log(sentence.includes("Pankaj")); // Output: true

startsWith()

Checks if a string starts with a specified value.

console.log(sentence.startsWith("Welcome")); // Output: true

endsWith()

Checks if a string ends with a specified value.

console.log(sentence.endsWith("Pankaj")); // Output: true

4. String Manipulation

Splitting Strings

Split a string into an array of substrings using .split().

let sentence = "Codes with Pankaj";
let words = sentence.split(" ");
console.log(words); // Output: ["Codes", "with", "Pankaj"]

Joining Strings

Combine array elements into a single string using .join().

let words = ["Codes", "with", "Pankaj"];
let sentence = words.join(" ");
console.log(sentence); // Output: Codes with Pankaj

Repeating Strings

Repeat a string multiple times using .repeat().

let text = "Hello!";
console.log(text.repeat(3)); // Output: Hello!Hello!Hello!

Padding Strings

Pad the beginning or end of a string using .padStart() and .padEnd().

let text = "5";
console.log(text.padStart(4, "0")); // Output: 0005
console.log(text.padEnd(4, "0"));   // Output: 5000

5. Special Characters in Strings

Escape Characters

To include special characters in a string, use escape sequences like for new lines or for tabs.

let text = "First Line\nSecond Line";
console.log(text);
// Output:
// First Line
// Second Line

Newlines

Use to create a new line within a string.

let text = "Hello,\nWorld!";
console.log(text);
// Output:
// Hello,
// World!

Tab Characters

Use to add a tab space within a string.

let text = "Hello\tWorld!";
console.log(text); // Output: Hello   World!

6. String Immutability

Strings in JavaScript are immutable, meaning that once a string is created, its value cannot be changed. However, you can create new strings based on existing ones.

Example:

let text = "Hello";
text[0] = "Y";  // This will not work
console.log(text);  // Output: Hello

7. Template Literals and String Interpolation

Template literals allow for multi-line strings and embedded expressions using ${}.

let name = "Pankaj";
let message = `Hello, ${name}! Welcome to Codes with Pankaj.`;
console.log(message); // Output: Hello, Pankaj! Welcome to Codes with Pankaj.

8. String Comparisons

You can compare strings using comparison operators like ===, ==, <, >, <=, >=.

Example:

let string1 = "apple";
let string2 = "banana";
console.log(string1 < string2);  // Output: true (because "apple" comes before "banana" lexicographically)

9. Working with Multi-line Strings

With template literals, you can create multi-line strings easily.

let multiLine = `This is the first line
This is the second line`;
console.log(multiLine);
// Output:
// This is the first line
// This is the second line

10. Conclusion

In this detailed tutorial, we explored the various aspects of strings in JavaScript. We covered how to create strings, use different string methods, manipulate strings, handle special characters, and work with template literals. By mastering these string operations, you'll be able to handle text in your JavaScript programs more effectively.

For more tutorials and examples, visit www.codeswithpankaj.com! Happy coding!


Last updated