Javascript Strings

See the following examples:

How to write a string in JavaScript.

There are three ways to write a string in JavaScript.

The first way is to write the string between two double quotes (" ")

The second way is to write the string between two single quotes (' ')

The third way is to write the string between two template literals

Examples

javascript
          "Write here the text inside the double quotes mark"
'Write here the text inside the single quotes mark'
`Write here the text inside template literals`
        

If the string begins with a double quotes, it must end with a double quotes. See the following example:

javascript
          console.log("firstName: Jeff");
        

In this example, we enclosed the text between double quotes

You can also write strings between single quotes, as shown in the following example:

javascript
          console.log('firstName: Jeff');
        

You can use a single quotes mark inside a double quotes mark. See the following example:

javascript
          console.log("My name is: 'Jeff'");
        

You can also use a double quotes mark inside a single quotes mark. See the following example:

javascript
          console.log('My name is: "Jeff"');
        

Escape Characters

Escape characters help us insert special characters into a string that are difficult to implement, such as single and double quotes. If we use quotes inside a string, we will encounter a problem if the quotes inside the string are the same type as the quotes that surround the string, as JavaScript interprets the quotes as the end of the string. See the following example:

javascript
          console.log("My name is: "Jeff"");
        

In this example, I show a SyntaxError.

To avoid this problem, inserting quotes into a string is done by using a backslash before adding the quotes to the string like this ("\") to prevent JavaScript from interpreting the quotes as the end of the string and considering them part of the string.

The backslash key is located above the Enter key on your keyboard and above the Return key on a Mac. See the following example:

javascript
          console.log("My name is: \"Jeff\"");
        

In this example, the double quotes were printed inside the string without any problems because the backslash tells the compiler that the next character is part of the string.

You can also print a single quote mark (') inside a string by adding a backslash before the single quote mark. See the following example:

javascript
          console.log('My name is: \"Jeff\'');
        

\n does the following: A new line within the same string. Look at the following example:

javascript
          console.log("First Name: Jeff \nLast Name: john");
        

Note that the second line has a space before it. Look at the output in the previous example and you'll see that the letter L is not below the letter F because there is a space after \n.

If I want to remove the space, I'll paste the word following \n into it. Look at the following example:

javascript
          console.log("First Name: Jeff \nLast Name: john");
        

In short, you can use

  • \" - to insert a double quotation mark.
  • \' - to insert a single quotation mark.
  • \n - to insert a new line.
  • \\ - to insert a backslash.

You can also use backticks . See the following example:

javascript
          console.log( ` My name is: 'Jeff' ` );
        

Concatenation

Concatenation combines (pastes) and joins two or more strings together and returns a new string. The + operator can be used to combine and join strings in JavaScript.

Syntax

javascript
          "String1" + "String2"
        

In the following example, we will combine two strings together:

javascript
          console.log("Jeff" + "john");
        

Note that there is no space between the first string, which contains the value of Jeff, and the second string, which contains the value of john. Give the computer a command to add a space.

There are three ways to add a space between strings.

The first way is to add a space after the end of the first string.

javascript
          console.log("Jeff " + "john");
        

The second way is to add a space before the beginning of the second string.

javascript
          console.log("Jeff" + "john");
        

The third way is to add two quotation marks " " to add a space between the first and second strings.

javascript
          console.log("Jeff" + " " + "john");
        

Strings can be stored in variables, and spaces can also be stored in a variable.

Look at the following example:

javascript
          let firstName = "Jeff";
let lastName = "john";
let space = " ";
console.log(firstName + space + lastName);
        

In this example, I combine the firstName variable with the lastName variable.

Length Property

Using length, you can find the length of a string and return the number of characters it contains. This is done by counting the number of characters and spaces in the string. See the following example:

javascript
          let greet = "Good Morning";
console.log(greet.length);
        

Note: that spaces are counted within this number.

String Methods

Index

Each character within the string is automatically assigned a number called an index. The index indicates the character's position within the string.

Any character in the string can be accessed using its index. The index starts at 0, meaning that the first character in the string has an index of 0, the second character has an index of 1, and so on.

For example, if we have a variable and assign it the value "Jeff" If we want to access the letter J and print it in console.log, we write the variable name and the index number between square brackets. See the following example:

javascript
          let userName = "Jeff";

console.log(userName[0]); // Outputs: J
console.log(userName[1]); // Outputs: e
console.log(userName[2]); // Outputs: f
console.log(userName[3]); // Outputs: f

        

CharAt() method

Returns the character you want to access by specifying its index.

As we mentioned before, the index starts at zero, meaning the index of the first character is index 0, the index of the second character is index 1, and so on. See the following example:

javascript
          let userName = "Jeff";
console.log(userName.charAt(0)); // Outputs: J
console.log(userName.charAt(1)); // Outputs: e

        

trim() method

The trim() method is used to remove spaces from the beginning and end of a string. See the following example:

javascript
          let str = "  JSBites  ";
console.log(str);  // Outputs: "  JSBites  "
console.log(str.trim()); // Outputs: "JSBites"
        

Note: Remove spaces from the beginning and end of the string.

trimStart() method

trimStart() is used to remove whitespace from the beginning of a string. See the following example:

javascript
          let str = "  JSBites  ";
console.log(str); // Outputs: "  JSBites  "
console.log(str.trimStart()); // Outputs: "JSBites  "
        

trimEnd() method

trimEnd() is used to remove whitespace from the end of a string. See the following example:

javascript
          let str = "  JSBites  ";
console.log(str); // Outputs: "  JSBites  "
console.log(str.trimEnd()); // Outputs: "  JSBites"
        

*Note:* The trim(), trimStart(), and trimEnd() methods only remove spaces at the edges of a string and do not affect spaces between words.

toLowerCase() method

This method changes all uppercase letters in a string to lowercase. See the following example:

javascript
          let userName = "Jeff";
console.log(userName . toLowerCase());
        

toUpperCase() method

This method changes all lowercase letters within a string to uppercase. See the following example:

javascript
          let userName = "Jeff";
console.log(userName. toUpperCase());
        

indexOf() method

indexOf searches for a specific value, whether a character, word, or phrase, within a string. Index returns the first position where the value appears in the string.

Syntax

javascript
          string.indexOf(value, index)
        

indexOf method takes two parameters:

  1. 1
    Value (required): The value you want to search for (letter, word, or phrase) within a string.
  2. 2
    Index (optional): The index from which the search begins. If no index is specified, the search will start at index 0.

See the following examples:

javascript
          let myName = "Jeff Jone";
console.log(myName.indexOf("J")); // Output: 0
console.log(myName.indexOf("Je")); // Output: 0
console.log(myName.indexOf("Jo")); // Output: 5
        

If the specified value is not found, it returns -1. See the following example:

javascript
          let myName = "Jeff Jone";
console.log(myName.indexOf("to", 6)); // Output: -1
console.log(myName.indexOf("Jo", 6)); // Output: -1
        

Note: indexOf is case-sensitive. See the following example:

javascript
          let myName = "Jeff Jone";
console.log(myName.indexOf("jo", 2)); // Output: -1
        

lastIndexOf() method

lastIndexOf searches for a specified value like indexOf, but it returns the index of the last occurrence of the value within the string because it searches from the end of the string to the beginning.

Syntax

javascript
          string.lastIndexOf(value, startingIndex);
        

See the following example:

javascript
          let str = "Welcome to JSBites.info";
console.log(str.lastIndexOf("o"));  // 22, last "o"
console.log(str.lastIndexOf("o", 10)); // 9, last "o" before index 10
        

Also, if the specified value is not found, it returns -1. See the following example:

javascript
          let myName = "Jeff Jone";
console.log(myName.lastIndexOf("N", 2))
        

slice() method

The slice() method allows you to extract a portion of a string and returns it as a new string without changing the original string.

Syntax

javascript
          string.slice(startIndex, endIndex)
        

The slice method takes two parameters:

  1. 1
    startIndex (required): The index at which to begin extraction.
  2. 2
    endIndex(optional):The index at which to stop extraction. The character at this index will not be included.

Note: If you do not add endIndex, the slice() method will extract the substring from the startIndex all the way to the end of the original string.

See the following examples:

javascript
          let myString = "I love coffee";
console.log(myString.slice(0)); // Output: I love coffee
console.log(myString.slice(7)); // Output: coffee

console.log(myString.slice(0, 5)); Output: I lov, 
        

Negative indices are calculated from the end of the string. -1 indicates the last character, -2 indicates the penultimate character, and so on. See the following examples:

javascript
          let myString = "I love code";
console.log(myString.slice(-1)); // Output: e
console.log(myString.slice(-4)); // Output: code
console.log(myString.slice(-4, -1)); // Output: code
        

Split() method

You can use the split() method to divide a string into substrings based on a specified separator, returning the results as an array.

syntax

javascript
          string.split(separator, limit)
        

split takes two parameters :

  1. 1
    separator (optional): The character or string to use as a delimiter. If not specified, the entire string is returned as a single-element array.
  2. 2
    limit (optional): An integer that specifies the maximum number of splits.

Look at the following examples:

No separator specified:

javascript
          let myString = "I love coffee";
console.log(myString.split()); // Output: ["I love coffee"]
        

Splitting all letters:

javascript
          let myString = "I love coffee";
console.log(myString.split("")); // Output: ["I", " ", "l", "o", "v", "e", ​​" ", "c", "o", "f", "f", "e", ​​"e"]

        

Splitting by a space:

javascript
          let myString = "I love coffee";
console.log(myString.split(" ")); // Output["I", "love", "coffee"]
        

Using a limit:

javascript
          let myString = "I love coffee";
console.log(myString.split(" ", 2)); // Output["I", "love"]
        

repeat() method

You can copy a string more than once using the repeat method.

Syntax

javascript
          string .repeat(count)
        

The repeat method takes one parameter:

  1. 1
    count (required): This indicates the number of times the string will be duplicated.

See the following example:

javascript
          let myString = "I love coffee";
console.log(myString.repeat(4));
        

includes method

The includes() method checks if a specified value exists within a string, returning true if it does and false if it doesn’t.

This method is case-sensitive.

Syntax

javascript
          String.includes(value, startingIndex)
        

includes takes two parameters:

  1. 1
    value (required): The substring or character to search for.
  2. 2
    startingIndex (optional): The index to start searching from. If no index is specified, the search will start from index 0.

See the following example:

javascript
          console.log(myString.includes("code")); // Output: true
        

In this example, the Includes method checks whether the string contains the word code or not.

See the following example:

javascript
          let myString = "I love code";
console.log(myString.includes("love", 4)); // Output: false
        

In this example, the Includes method checks whether the string contains the word love starting at index 4.

Note: The Includes method is case-sensitive. See the following example:

javascript
          let myString = "I love code";
console.log(myString.includes("Love")); // Output: false
        

startsWith() method

The startsWith() method checks if a string begins with a specified value, returning true if it does and false if not.

Syntax

javascript
          string.startsWith(value, startingIndex);
        

startsWith method takes two parameters:

  1. 1
    value: The string or character to check at the start of the string (required).
  2. 2
    startingIndex (optional): The position to start the search. If omitted, it defaults to 0.

See the following examples:

javascript
          let str = "Welcome to JSBites.info";
console.log(str.startsWith("Wel"));          // true
console.log(str.startsWith("Wel", 1));       // false
console.log(str.startsWith("JSBites", 11));  // true
console.log(str.startsWith("jsbites", 11)); // false, case-sensitive
        

endsWith() method

The endsWith() method is similar to startsWith() but endsWith() checks if a string ends with a specified value, returning true if it does and false if not.

Syntax:

javascript
          string.endsWith(value, startingIndex);
        

See the following examples:

javascript
            let str = "Welcome to JSBites.info";
  console.log(str.endsWith("info"));          // true
  console.log(str.endsWith("info", 21));       // false
  console.log(str.endsWith("inf", 22));  // true
  console.log(str.endsWith("INFO")); // false, case-sensitive