# JavaScript Strings Explained: From length to includes()

### ***What the string is in JavaScript?***

A JavaScript ***string*** is a sequence of characters, typically used to represent ***text***.

We can either use a ***single quote*** `('')` or a ***double quote*** `("")` or a ***back-ticks*** `(``)` to create a ***string***. We can use either of the ***three***, but it is recommended to be consistent with your choice throughout your code.

```javascript
// Using Single Quote
let firstName = 'Ayan';
console.log(firstName);

// Using Double Quote
let middleName = "Shahid";
console.log(middleName);

//Using Backticks
let lastName = `Khan`;
console.log(lastName);
```

<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text">You can create a <strong><em>multiline</em></strong> <strong><em>string</em></strong> using <strong><em>backticks</em></strong> <code>(``)</code>.</div>
</div>

> Strings are immutable.

![](https://cdn.hashnode.com/uploads/covers/695114b01f48b622b5631972/cd2ea58c-51e6-4564-814c-964aa50324b5.jpg align="center")

### *Finding the length of a String*

You can find the `length` of a string using the `length` property.

```javascript
let s = 'JavaScript';
let len = s.length;

console.log("String Length: " + len);
```

### **What Is Bracket Notation, and How Do You Access Characters from a String?**

In JavaScript, `strings` are treated as `sequences of characters`, and each `character` in a `string` can be accessed using `bracket notation`. This allows you to retrieve a `specific` character from a `string` based on its position, which is called its `index`.

An `index` is the `position` of a character within a `string`, and it is `zero-based`. This means that the `first` character of a string has an index of `0`, the `second` character has an index of `1`, and so on.

For example, in the string `hello`, the character `h` is at index `0`, `e` is at index `1`, `l` is at index `2`, and so on.

`Bracket notation` uses square brackets (`[]`) and the `index` of the character you want to access. Let’s look at an example:

```javascript
let greeting = "hello";
console.log(greeting[1]); // "e"
```

In this example, we can access the character at index `1`, which is `e`.

To get the `last` character of a `string`, you can use the `length` of the string `minus one`. The `length` property of a `string` tells you how many characters it contains, so to access the `last` character, you would subtract `one` from the length:

```javascript
let greeting = "hello";
console.log(greeting[greeting.length - 1]); // "o"
```

In this case, the `length` of `hello` is `5`, and the last character (`o`) is at index `4` which is `5 - 1`.

If you want to get `multiple` characters, you can use `bracket` notation like this:

```javascript
let greeting = "hello";
let firstTwo = greeting[0] + greeting[1]; // "he"
console.log(firstTwo);
```

In this example, we are `concatenating` the `first` and `second` characters using `bracket` notation to form the string `he`.

`Bracket notation` is useful when you need to access `specific` characters in a string, such as extracting `initials` from a name or checking a specific letter for validation.

![](https://cdn.hashnode.com/uploads/covers/695114b01f48b622b5631972/50d0afe1-31fb-4d32-b703-b3f1e4627abd.jpg align="center")

### **How Can You Find the** `Position` **of a** `Substring` **in a** `String` `indexOf` method?

When working with strings in JavaScript, there may be times when you need to locate the position of a specific `substring` within a larger string.

A `substring` is a sequence of characters that appears `within` a larger string. For example, in the string `hello world`, `hello` and `world` are `substrings`.

To locate the position of a `substring` inside of a `string`, you can use the `indexOf()` method.

The `indexOf()` method in JavaScript allows you to search for a `substring` within a `string`.

If the substring is found, `indexOf()` returns the `index (or position)`of the `first occurrence` of that `substring`. If the `substring` is not found, `indexOf()` returns `-1`, which indicates that the search was unsuccessful.

The `indexOf()` method takes `two` arguments: the first is the `substring` you want to find within the larger `string`, and the second is an `option starting position` for the search. If you don’t provide a `starting` position, the search will begin at the `start` of the string.

In this context, an `argument` is a value you give to a `function` or method when you `call` it, enabling that `function` or `method` to perform its task using the specific `information` you provide. You will learn more about `arguments` in future lessons.

Here is an example of using the `indexOf()` method to find the position for the string `awesome`:

```javascript
let sentence = "JavaScript is awesome!";
let position = sentence.indexOf("awesome!");
console.log(position); // 14
```

In this example, the word `awesome` starts at index `14` in the string `JavaScript is awesome!`, so the `indexOf()` method returns `14`.

Now, let's see what happens when the `substring` isn't found:

```javascript
let sentence = "JavaScript is awesome!";
let position = sentence.indexOf("fantastic");
console.log(position); // -1
```

Since the word `fantastic` does not appear in the `string`, the method returns `-1`.

You can also specify where to `begin` searching within the `string` by providing a `second` argument to `indexOf()`. Here's an example:

```javascript
let sentence = "JavaScript is awesome, and JavaScript is powerful!";
let position = sentence.indexOf("JavaScript", 10);
console.log(position); // 27
```

In this case, the search for `JavaScript` begins after the `10th` character, and so the `second` occurrence of `JavaScript` is found at index `27`.

It is important to note that the `indexOf()` method is `case sensitive`.

```javascript
console.log("freeCodeCamp".indexOf("F")) // -1
```

Using `indexOf()` can be very useful when you need to check if a `substring` is present in a `string` and to determine its `position` for further operations.

![](https://cdn.hashnode.com/uploads/covers/695114b01f48b622b5631972/8b9b16e4-0599-4cb8-a489-736a4eb82981.jpg align="center")

### **How** `ASCII` **Does It Work with** `charCodeAt()` **and** `fromCharCode()`**?**

In this lesson, we will explore what `ASCII` is, how it works, and how JavaScript methods like `charCodeAt()` and `fromCharCode()` relate to character encoding. While JavaScript strings use `Unicode (UTF-16)` internally, `ASCII` values match the first `128` Unicode characters, which is why `ASCII`\-based examples work in JavaScript.

ASCII is a system for encoding characters such as `letters`, `digits`, and `symbols` into numerical values. Each character is mapped to a specific number.

For example, the capital letter `A` is represented by the number `65` in ASCII, while the lowercase `a` is represented by `97`. This encoding allows computers to store and manipulate text.

The ASCII standard covers `128` characters including:

*   `Uppercase` and `lowercase` English letters (`A-Z, a-z`).
    
*   `Numbers` `(0-9)`.
    
*   Common punctuation marks and symbols `(!, @, #, and so on)`.
    
*   Control characters (such as `newline` and `tab`).
    

In JavaScript, you can access the `numeric code` of a `character` using the `charCodeAt()` method. This method returns the `UTF-16` code unit of the character at a `specified` index. For the first `128` characters, this value matches the `ASCII` code.

Let’s take a look at an example:

```javascript
let letter = "A";
console.log(letter.charCodeAt(0));  // 65
```

In this example, `A` is the first character of the string, and calling `charCodeAt(0)` returns its numeric code (which matches its `ASCII` value for basic `Latin` characters), `65`.

You can also use this method with other characters to find their numeric code values:

```javascript
let symbol = "!";
console.log(symbol.charCodeAt(0));  // 33
```

Here, the numeric code for the exclamation mark `!` is returned as `33` (which matches its `ASCII` value).

While `charCodeAt()` helps you retrieve the numeric code of a character, the `fromCharCode()` method allows you to do the opposite: convert a UTF-16 code unit (which matches ASCII for basic characters) into its corresponding character.

Let's see this in action:

```javascript
let char = String.fromCharCode(65);
console.log(char);  //  A
```

In this example, `fromCharCode(65)` converts the numeric code `65` (which matches the ASCII value for `A`) back to the character `A`.

Another example would be converting the number `97` to its corresponding lowercase letter:

```javascript
let char = String.fromCharCode(97);
console.log(char);  // a
```

These methods are particularly useful when you need to manipulate or compare characters based on their numeric code values.

For instance, you might use `charCodeAt()` to check if a character is uppercase, lowercase, or a digit by comparing its ASCII value.

On the other hand, `fromCharCode()` can be used to dynamically generate characters from their ASCII codes.

![](https://cdn.hashnode.com/uploads/covers/695114b01f48b622b5631972/27021b87-5b8c-45e2-8142-3a06526bc2f0.jpg align="center")

### **How Can You Test if a** `String` **Contains a** `Substring` `includes()` method?

When working with `strings` in JavaScript, there are many cases where you might need to check whether a string contains a specific `substring`, which is a smaller part of that `string`.

For example, you might want to check if a user's input includes a specific word or character before performing some action. One way to achieve this is by using the `includes()` method.

The `includes()` method is used to check if a `string` contains a specific `substring`. If the `substring` is found within the `string`, the method returns `true` otherwise, it returns `false`.

Here's the basic syntax:

```javascript
string.includes(searchValue);
```

For the syntax, the `searchValue` is the substring you want to look for within the string. And here's an example:

```javascript
let phrase = "JavaScript is awesome!";
let result = phrase.includes("awesome");

console.log(result);  // true
```

In this example, the word `awesome` is found within the string `JavaScript is awesome!`, so the `includes()` method returns `true`.

It's important to note that the `includes()` method is `case-sensitive`. This means that the exact match of the characters is required, including their case.

```javascript
let phrase = "JavaScript is awesome!";
let result = phrase.includes("Awesome");

console.log(result);  // false
```

Since `Awesome` (with an uppercase `A`) does not match `awesome` (with a lowercase `a`), the result is `false`.

You can also use the `includes()` method to check for a substring starting at a specific index in the string by providing a second parameter:

```javascript
let text = "Hello, JavaScript world!";
let result = text.includes("JavaScript", 7);

console.log(result);  // true
```

Here, the search for the substring `JavaScript` starts from the 7th position in the string, ensuring it skips any characters before this position.

The `includes()` method only returns a `true` or `false` result. It does not provide information on where the substring is located in the string or how many times it occurs. If you need that level of detail, other methods, such as the `indexOf()` method might be more suitable.

![](https://cdn.hashnode.com/uploads/covers/695114b01f48b622b5631972/3c25eb99-d370-4d5b-a789-946c22e5fa71.jpg align="center")

### **How Can You Extract a** `Substring` **from a** `String` `slice()` method?

When working with `strings` in JavaScript, you often need to extract a portion or `substring` from a larger string.

For example, you may want to `extract` part of a word, a specific character sequence, or just a fragment of a sentence.

JavaScript provides several methods for this task, one of the most commonly used being the `slice()` method.

The `slice()` method allows you to extract a portion of a `string` and returns a `new string`, without modifying the `original string`. It takes `two` parameters: the `starting index` and the optional `ending index`.

Here's the basic syntax:

```javascript
string.slice(startIndex, endIndex);
```

`startIndex` `(inclusive)`is the position where the extraction starts. `endIndex` `(exclusive)` is where the extraction ends. If not provided, `slice()` extracts until the `end` of the string.

Let's look at a simple example of extracting part of a string:

```javascript
let message = "Hello, world!";
let greeting = message.slice(0, 5);

console.log(greeting);  // Hello
```

In this example, `slice(0, 5)` extracts characters starting from index `0` up to but not including index `5`. As a result, the word `Hello` is extracted.

If you omit the `second` parameter, `slice()` will extract everything from the start index to the `end` of the string:

```javascript
let message = "Hello, world!";
let world = message.slice(7);

console.log(world);  // world!
```

Here, `slice(7)` extracts the string from index `7` to the end of the string, resulting in `world!`.

You can also use `negative` numbers as `indexes`. When you use a negative number, it counts backward from the `end` of the string:

```javascript
let message = "JavaScript is fun!";
let lastWord = message.slice(-4);

console.log(lastWord);  // fun!
```

In this case, `slice(-4)` extracts the last four characters from the string, giving us `fun!`.

Let's say you want to extract a section from the `middle` of a string. You can provide both the `starting` and `ending` indexes to precisely control which part of the string you want:

```javascript
let message = "I love JavaScript!";
let language = message.slice(7, 17);

console.log(language);  // JavaScript
```

Here, `slice(7, 17)` extracts the `substring` `starting` at index 7 and `ending` right before index `17`, which is the word `JavaScript`.

The `slice()` method is a powerful tool for extracting parts of a string in JavaScript.

You specify the `start` and `end` indexes, and the method returns a new string that contains the extracted portion.

With options for positive, negative, and omitted indexes, you can adapt it to various situations without altering the original string.

![](https://cdn.hashnode.com/uploads/covers/695114b01f48b622b5631972/0dbfa12f-507d-42bb-84b4-50e111570232.jpg align="center")

### Working with `String` Formatting Methods

`toUpperCase()` and `toLowerCase()` Methods:

### `toUpperCase()` Method

The `toUpperCase()` method converts all the characters to uppercase letters and returns a new string with all uppercase characters. This is useful when you want to emphasize text or create consistency in the format of strings.

Let's see an example:

```javascript
let greeting = "Hello, World!";
let uppercaseGreeting = greeting.toUpperCase();
console.log(uppercaseGreeting);  // "HELLO, WORLD!"
```

In this code, the `toUpperCase()` method transforms the entire string into uppercase letters.

### `toLowerCase()` Method

On the flip side, the `toLowerCase()` method converts all characters in a string to lowercase. This is helpful when you need to standardize input, such as when comparing user-provided text or making case-insensitive checks.

Let's look at an example:

```javascript
let shout = "I AM LEARNING JAVASCRIPT!";
let lowercaseShout = shout.toLowerCase();
console.log(lowercaseShout);  // "i am learning javascript!
```

The `toLowerCase()` method converts all characters to lowercase, making the string less aggressive, while leaving the original string unchanged.

These methods are particularly useful for standardizing text input, making case-insensitive comparisons, and ensuring design consistency.

![](https://cdn.hashnode.com/uploads/covers/695114b01f48b622b5631972/c30497b3-622e-4290-b289-ca153bbe4b39.jpg align="center")

### **How Can You** `Trim` `Whitespace` (empty spaces) **from a String?**

When working with strings in JavaScript, it's common to encounter unwanted `whitespace` at the beginning or end of a string. `Whitespace` can interfere with operations like comparison, storage, or display, which is why it's important to know how to remove it efficiently.

In this lesson, we'll explore how you can trim `whitespace` using JavaScript's `trim()`, `trimStart()`, and `trimEnd()` methods.

`Whitespace` refers to spaces, tabs, or line breaks that occur in a string but are not visible characters. For example:

```javascript
let greeting = "   Hello, world!   ";
```

In this case, there are spaces before and after the visible text, `Hello, world!`.

The `trim()` method is the most commonly used way to remove whitespace from both the beginning and the end of a string. Here's an example:

```javascript
let message = "   Hello!   ";
console.log(message); // "   Hello!   "
let trimmedMessage = message.trim();
console.log(trimmedMessage);  // "Hello!"
```

In this case, the `trim()` method removes all the leading and trailing spaces, leaving just `Hello!`. Note that any whitespace within the string (between words, for example) is left untouched by `trim()`.

Sometimes, you may only want to remove whitespace from either the beginning or the end of a string, but not both. This is where `trimStart()` and `trimEnd()` come in.

`trimStart()` removes whitespace from the beginning (or start) of the string.

```javascript
let greeting = "   Hello!   ";
console.log(greeting);  // "   Hello!   "
let trimmedStart = greeting.trimStart();
console.log(trimmedStart);  // "Hello!   "
```

`trimEnd()` removes whitespace from the end of the string.

```javascript
let greeting = "   Hello!   ";
console.log(greeting);  // "   Hello!   "
let trimmedEnd = greeting.trimEnd();
console.log(trimmedEnd);  // "   Hello!"
```

These methods give you more precise control over which part of the string you want to clean up.

![](https://cdn.hashnode.com/uploads/covers/695114b01f48b622b5631972/7de0f7e5-5734-4d6c-8859-816a2fe0d5b6.jpg align="center")

### **How Can You** `Replace` **Parts of a String with Another** `replace()` **method?**

In JavaScript, there are many scenarios where you may need to `replace` a portion of a string with `another` string.

For instance, you might need to update user information in a URL, change the formatting of dates, or correct errors in user-generated content.

The `replace()` method in JavaScript allows you to find a specified value (like a word or character) in a string and `replace` it with `another` value. The method returns a `new string` with the `replacement` and leaves the `original` unchanged because JavaScript strings are immutable.

Here is the basic syntax:

```javascript
string.replace(searchValue, newValue);
```

`searchValue` is the value you want to search for in the string. It can be either a `string` or a `regular expression (regex)`, which describes `patterns` in text. This allows you to search for and manipulate strings in a flexible and powerful way. You'll learn more about `regular` expressions in future lessons.

The `newValue` is the value that will replace the `searchValue`. Here's a simple example:

```javascript
let text = "I love JavaScript!";
console.log(text); // "I love JavaScript!"
let newText = text.replace("JavaScript", "coding");
console.log(newText);  // "I love coding!"
```

In this example, the word `JavaScript` is found within the string and is replaced with `coding`.

The `replace()` method is `case-sensitive`, meaning that it will only find exact matches of the `searchValue`. For example:

```javascript
let sentence = "I enjoy working with JavaScript.";
console.log(sentence);  // "I enjoy working with JavaScript."
let updatedSentence = sentence.replace("javascript", "coding");
console.log(updatedSentence);  // "I enjoy working with JavaScript."
```

Here, since `javascript` (with lowercase `j`) does not match `JavaScript` (with uppercase `J`), the replacement is not made.

By default, the `replace()` method will only replace the `first occurrence` of the `searchValue`. If the value appears `multiple` times in the string, only the `first one` will be replaced:

```js
let phrase = "Hello, world! Welcome to the world of coding.";
console.log(phrase);  // "Hello, world! Welcome to the world of coding."
let updatedPhrase = phrase.replace("world", "universe");
console.log(updatedPhrase);  // "Hello, universe! Welcome to the world of coding."
```

Notice that only the first occurrence of `world` is replaced with `universe`.

The `replace()` method in JavaScript is a powerful and flexible tool for string manipulation.

While it's ideal for `straightforward` replacements, understanding its `case` `sensitivity` and default behavior (like replacing only the `first` occurrence) can help you use it more effectively.

![](https://cdn.hashnode.com/uploads/covers/695114b01f48b622b5631972/fad22e24-d4e5-410f-8ac4-87a737cabf1d.jpg align="center")

### **How Can You Repeat a String** `x` **Number of Times** `repeat()` **method?**

When working with JavaScript, you may encounter situations where you need to repeat a string a specific `number` of times.

Whether you're generating `repeated patterns` or simply `duplicating text`, the `repeat()` method provides a simple and effective way to achieve this.

The `repeat()` method is a built-in function in JavaScript that allows you to `repeat` a string a `specified number` of times. Here is the basic syntax:

```javascript
string.repeat(count);
```

`string` is the string that you want to repeat, and `count` is the number of times you want the string to be repeated. Here's an example:

```javascript
let word = "Hello!";
let repeatedWord = word.repeat(3);
console.log(repeatedWord);  // "Hello!Hello!Hello!"
```

In this case, the string `Hello!` is repeated three times, resulting in `Hello!Hello!Hello!`.

While the `repeat()` method is useful, there are a few exceptions and limitations to keep in mind.

The `count` parameter must be a non-negative number. If you pass a negative number, JavaScript will throw a `RangeError`.

```javascript
let word = "Test";
console.log(word.repeat(-1));  // Throws RangeError: Invalid count value
```

The `count` must be a `finite` number. If you try to repeat a string an `infinite` number of times or use `Infinity` as the count, you will also get a `RangeError`.

In JavaScript, `Infinity` is a special value that represents an `infinite` quantity. It's used to denote numbers that are `larger` than any finite number.

```javascript
let word = "Test";
console.log(word.repeat(Infinity));  // Throws RangeError: Invalid count value
```

If the count is not an `integer` (such as a decimal like `2.5`), the `repeat()` method will round it `down` to the nearest integer.

```javascript
let word = "Test";
console.log(word.repeat(2.5));  // "TestTest"
```

If you pass `0` as the count, the `repeat()` method will return an `empty` string.

```javascript
let word = "Test";
console.log(word.repeat(0));  // ""
```

The `repeat()` method can simplify tasks that involve string duplication, making your code more concise and readable.

Whether you're generating repeated text patterns or filling a space with characters, `repeat()` can save you from writing loops or more complex code.

You are not limited to passing a number directly into the `repeat()` method. You can also pass a variable that stores a number value.

![](https://cdn.hashnode.com/uploads/covers/695114b01f48b622b5631972/6742473c-4594-47f9-a71d-d327f4a07777.jpg align="center")

```javascript
let count = 4;
let word = "Test";
let repeatedWord = word.repeat(count);
console.log(repeatedWord); // TestTestTestTest
```

In this example, the `count` variable stores the number of repetitions. This can be useful when the number of repetitions depends on user input or other dynamic values in your program.

![](https://cdn.hashnode.com/uploads/covers/695114b01f48b622b5631972/849ac24e-d02d-44c4-952b-b07969042dee.jpg align="center")

<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text">Now it’s your turn. Open the console, experiment with these methods, and see what JavaScript strings can really do.</div>
</div>
