Skip to main content

Javascript Strings

Strings are used to represent text. which is a sequence of characters enclosed in quotes (either single quotes or double quotes).

Examples of string literals:

let message = "Hello, CSC!"; // using single quotes
let name = "CSC"; // using double quotes
let str = ""; // an empty string

String Length

In JavaScript, you can get the length of a string using the length property. The length property returns the number of characters in the string.

As an example:

const str = "Hello, world!";
console.log(str.length); // Output: 13

In this example:

  • The length property returns 13, which is the number of characters in the string 'Hello, world!'.

Escape Character

An escape character is a backslash () followed by a character. The backslash tells JavaScript to treat the character that follows in a special way.

Here are some common escape characters in JavaScript:

  • \' - single quote
  • \" - double quote
  • \\ - backslash
  • \n - newline
  • \t - tab
  • \b - backspace
  • \r - carriage return
  • \f - form feed

This example showcases the application of several escape characters:

const str = 'She said, "Don\'t forget to buy milk."';
console.log(str); // Output: She said, "Don't forget to buy milk."

In this example:

  • The string contains a double quote and a single quote.
  • To include the single quote within the string, we used the escape character \ before the single quote.

String Example

Editor

Loading...