Strings in JavaScript

Strings in JavaScript

Table of contents

In JavaScript, a string is a sequence of characters used to represent text. Strings are used to store and manipulate textual data. They are created by enclosing text within single quotes (' '), double quotes (" "), or backticks (` `). Here are different ways to define a string in JavaScript:

  1. Using Single Quotes:

     let myString = 'This is a string using single quotes.';
    
  2. Using Double Quotes:

     let anotherString = "This is a string using double quotes.";
    
  3. Using Backticks (Template literals):

    Template literals introduced in ES6 allow for more flexible string definitions. They allow embedding expressions within strings using ${}.

     let name = 'John';
     let age = 30;
     let templateString = `My name is ${name} and I'm ${age} years old.`;
    

Strings in JavaScript are immutable, meaning their content cannot be changed once they are created. However, you can create new strings based on existing ones through various methods or string manipulation functions. JavaScript provides numerous built-in string methods to perform operations like concatenation, splitting, substring extraction, searching, and more.

String Methods

There are numerous string methods provided by JavaScript for our use. Not all of them are important, and it's not easy to memorize all of them. Only the important ones, which are used on a daily basis, will be discussed.

When you console log the string, you'll see that it has one property and numerous methods.

  • length:

    The length property in JavaScript is used to determine the number of characters in a string. It returns the count of characters in a string, including letters, numbers, spaces, and punctuation.

    Example:

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

    In this example, myString.length will output 13 because the string "Hello, World!" contains 13 characters including letters, a comma, a space, and an exclamation mark.

  • slice():

    The slice() method in JavaScript extracts a section of a string and returns it as a new string, without modifying the original string.

    Syntax:

      string.slice(startIndex, endIndex)
    

    Parameters:

    • startIndex: The index where the extraction begins.

    • endIndex (optional): The index at which the extraction ends (not included in the extracted string). If not specified, extraction continues to the end of the string.

Example:

    const str = "Hello, World!";
    const sliced = str.slice(7, 12);
    console.log(sliced); // Output: "World"

In the example, str.slice(7, 12) extracts the characters from index 7 (inclusive) to index 12 (exclusive) from the str string, resulting in the string "World".

  • substring():

    The substring() method in JavaScript is used to extract a portion of a string and return it as a new string. It takes two parameters: the starting index and the ending index (optional). If the ending index is not specified, substring() will extract from the start index to the end of the string.

    Example:

      const str = "This is a sample string";
      const extracted = str.substring(5, 10);
      console.log(extracted); // Output: "is a "
    

    In this example, substring(5, 10) extracts characters from index 5 (inclusive) to index 10 (exclusive) from the string str. The extracted substring is "is a ". If the second parameter (ending index) is omitted, the substring would extend to the end of the string.

  • substr():
    The substr() method in JavaScript extracts a portion of a string, starting from a specified index to the number of characters indicated.

    Syntax:

      string.substr(startIndex, length)
    
    • startIndex: The index from which to start extracting characters. If negative, it represents an offset from the end of the string.

    • length (optional): The number of characters to extract. If omitted, it extracts characters until the end of the string.

Example:

    const sentence = "The quick brown fox";
    console.log(sentence.substr(4, 5)); // Outputs: "quick"
    console.log(sentence.substr(10)); // Outputs: "brown fox"
    console.log(sentence.substr(-3)); // Outputs: "fox"

In this example:

  • sentence.substr(4, 5) extracts 5 characters starting from the index 4, which returns "quick".

  • sentence.substr(10) starts from index 10 and extracts characters until the end, resulting in "brown fox".

  • sentence.substr(-3) starts 3 characters from the end of the string and extracts until the end, resulting in "fox".

  • replace():

    The replace() method in JavaScript is used to replace the first occurrence of a specified string or pattern within a larger string with another string.

    Syntax:

      string.replace(searchValue, replaceValue)
    
    • searchValue: The string or regular expression to be replaced.

    • replaceValue: The string that replaces the found value.

Example:

    const sentence = "I love JavaScript. JavaScript is amazing!";
    const newSentence = sentence.replace("JavaScript", "coding");
    console.log(newSentence);
    // Output: "I love coding. JavaScript is amazing!"

In this example, the replace() method is used to find first occurrences of "JavaScript" in the sentence string and replace them with "coding", creating a new string assigned to newSentence.

  • replaceAll():

    The replaceAll() method in JavaScript is used to replace all occurrences of a specified substring within a string with another substring.

    Syntax:

      string.replaceAll(searchValue, replaceValue);
    
    • searchValue: The substring you want to replace.

    • replaceValue: The new substring to replace all occurrences of searchValue.

Example:

    const originalString = "Hello, World! Hello!";
    const replacedString = originalString.replaceAll("Hello", "Hi");

    console.log(replacedString);

In this example, replaceAll() is used to replace all occurrences of the substring "Hello" with "Hi" in the originalString. The result, replacedString, would be "Hi, World! Hi!".

  • toUpperCase():

    The toUpperCase() method in JavaScript is used to convert all characters in a string to uppercase. It doesn't modify the original string but returns a new string with all characters converted to uppercase.

    Example:

      let text = "hello, world!";
      let upperCaseText = text.toUpperCase();
      console.log(upperCaseText); // Output: "HELLO, WORLD!"
    

    In this example, the toUpperCase() method converts the string stored in the text variable to uppercase and stores the result in the upperCaseText variable without altering the original string.

  • toLowerCase():

    The toLowerCase() method in JavaScript is used to convert all characters in a string to lowercase. It doesn't modify the original string but returns a new string with all alphabetic characters converted to lowercase.

    Example:

      let originalString = "Hello World";
      let lowerCaseString = originalString.toLowerCase();
    
      console.log(lowerCaseString); // Outputs: "hello world"
    

    In this example, toLowerCase() converts the string "Hello World" to an all-lowercase string, creating a new string assigned to the variable lowerCaseString. The original string, originalString, remains unchanged.

  • concat():

    The concat() method in JavaScript is used to combine or concatenate two or more strings and return a new string containing the combined text.

    Syntax:

      string.concat(string1, string2, ..., stringN)
    

    Example:

      const str1 = "Hello, ";
      const str2 = "World!";
      const combinedString = str1.concat(str2);
    
      console.log(combinedString); // Output: Hello, World!
    

    In this example, str1.concat(str2) combines str1 and str2, creating a new string combinedString with the text "Hello, World!".

  • trim():

    The trim() method in JavaScript removes whitespace (spaces, tabs, line breaks) from both ends of a string.

    Example:

      const str = "   Hello, World!   ";
      const trimmed = str.trim();
      console.log(trimmed); // Outputs: "Hello, World!"
    
  • trimStart():

    The trimStart() method in JavaScript removes whitespace characters from the beginning (start) of a string and returns the modified string. It does not modify the original string, but instead, it creates and returns a new string with the leading whitespace characters removed.

    Example:

      const str = "   Hello, world!   ";
      const trimmedString = str.trimStart();
    
      console.log(trimmedString); // Outputs: "Hello, world!   "
    

    In this example, trimStart() removes the leading spaces from the original string str, producing the modified string trimmedString.

  • trimEnd():

    The trimEnd() method in JavaScript removes whitespace characters from the end (right side) of a string. It returns a new string with the trailing whitespaces removed.

    Example:

      const text = "   Hello, World!    ";
      const trimmedText = text.trimEnd();
      console.log(trimmedText); // Output: "   Hello, World!"
    

    In this example, trimEnd() removes the whitespace characters at the end of the string text, leaving the leading spaces intact. The resulting trimmedText variable contains the original string without trailing whitespaces.

  • padStart():

    The padStart() method is used to pad a string with another string until it reaches a specified length. This padding occurs at the beginning of the string.

    Syntax:

      string.padStart(targetLength, padString)
    
    • targetLength: The final length the string should reach.

    • padString (optional): The string to pad the current string with. If not specified, it pads with spaces.

Example:

    let str = "7";
    let paddedStr = str.padStart(4, "0");
    console.log(paddedStr); // Outputs: "0007"

In this example:

  • The initial string is "7".

  • padStart(4, "0") is used to pad the string with "0" at the beginning until it reaches a length of 4.

  • The resulting string is "0007", padded with "0" to reach the length of 4.

  • padEnd():

    The padEnd() method is used to pad the end of a string with a specified character(s) until the resulting string reaches a given length. If the provided string is already equal to or longer than the specified length, it returns the original string.

    Syntax:

      string.padEnd(targetLength [, padString])
    
    • targetLength: The desired length of the resulting string.

    • padString (optional): The string to pad with; it defaults to a space character.

Example:

    const originalString = 'Hello';
    const paddedString = originalString.padEnd(10, '-');

    console.log(paddedString); // Outputs: "Hello-----"

In the example, the padEnd() method pads the original string 'Hello' with hyphens ('-') until the resulting string reaches a length of 10 characters. The output is "Hello-----" because it added five hyphens to the end of the original string to achieve the specified length.

  • charAt():

    The charAt() method in JavaScript is used to retrieve a single character from a string at a specified index.

    Syntax:

      string.charAt(index)
    
    • string is the string from which to extract the character.

    • index is the position of the character to retrieve. The index is a zero-based value.

Example:

    const str = "Hello, World!";
    console.log(str.charAt(7)); // Output: W

In this example, str.charAt(7) retrieves the character at index 7 in the string "Hello, World!", which is 'W'.

  • charCodeAt():

    The charCodeAt() method in JavaScript is used to retrieve the Unicode value of a character at a specified index within a string.

    Syntax:

      string.charCodeAt(index)
    
    • string is the string containing the character.

    • index is the position of the character for which the Unicode value needs to be obtained.

Example:

    const str = "Hello";
    console.log(str.charCodeAt(0)); // Outputs: 72 (Unicode value for 'H')
    console.log(str.charCodeAt(3)); // Outputs: 108 (Unicode value for 'l')

In the example, str.charCodeAt(0) retrieves the Unicode value of the character at index 0 in the string "Hello," which is 72, representing the character 'H'. Similarly, str.charCodeAt(3) fetches the Unicode value of the character 'l' at index 3, which is 108.

  • split():

    The split() method in JavaScript is used to split a string into an array of substrings based on a specified separator.

    Syntax:

      string.split(separator, limit)
    
    • string: The original string that will be split.

    • separator: Specifies the character or regular expression used to determine where to split the string. If omitted, the entire string becomes the only element in the resulting array.

    • limit (Optional): A number specifying the maximum number of splits to be found. The remainder of the string is not included in the resulting array if the limit is reached.

Example:

    const sentence = "The quick brown fox";
    const words = sentence.split(" "); // Splits the string into an array of words using space as the separator
    console.log(words); // Output: ["The", "quick", "brown", "fox"]

In the given example, the split(" ") method splits the sentence string into an array of words using the space character as the separator. The resulting array contains each word as a separate element.