# JavaScript Strings

In this article, we learn about strings and their methods

### **What is String?**

> a string is a sequence of characters enclosed in single quotes (''), double quotes ("") or backticks (\`\`).

Strings are immutable, meaning their values cannot be changed once created

Here are some commonly used string methods:

## slice()

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

### Syntax

```javascript
slice(indexStart)
slice(indexStart, indexEnd)
```

```javascript
const str = 'The quick brown fox jumps over the lazy dog.';

console.log(str.slice(31));
// Expected output: "the lazy dog."

console.log(str.slice(4, 19));
// Expected output: "quick brown fox"

console.log(str.slice(-4));
// Expected output: "dog."

console.log(str.slice(-9, -5));
// Expected output: "lazy"
```

## **substring()**

The `substring()` method returns the part of the `string` from the start index up to and excluding the end index.

### Syntax

```javascript
substring(indexStart)
substring(indexStart, indexEnd)
```

```javascript
const str = 'Mozilla';

console.log(str.substring(1, 3));
// Expected output: "oz"

console.log(str.substring(2));
// Expected output: "zilla"
```

## **trim()**

The `trim()` method removes whitespace from both ends of a string and returns a new string, without modifying the original string.

### Syntax

```javascript
trim()
```

```javascript
const greeting = ' Hello world! ';

console.log(greeting); // Expected output: " Hello world! ";

console.log(greeting.trim()); // Expected output: "Hello world!";
```

## trimEnd()

The `trimEnd()` method removes whitespace from the end of a string and returns a new string, without modifying the original string.

### Syntax

```javascript
trimEnd()
```

```javascript
const greeting = '   Hello world!   ';

console.log(greeting);
// Expected output: "   Hello world!   ";

console.log(greeting.trimEnd());
// Expected output: "   Hello world!";
```

### **trimStart()**

The `trimStart()` method removes whitespace from the beginning of a string and returns a new string, without modifying the original string.

```javascript
trimStart()
```

```javascript
const greeting = '   Hello world!   ';

console.log(greeting);
// Expected output: "   Hello world!   ";

console.log(greeting.trimStart());
// Expected output: "Hello world!   ";
```

## toLowerCase()

The `toLowerCase()` method returns the calling string value converted to lower case

### Syntax

```javascript
toLowerCase()
```

```javascript
const sentence = 'The quick brown fox jumps over the lazy dog.';

console.log(sentence.toLowerCase());
// Expected output: "the quick brown fox jumps over the lazy dog."
```

# toUpperCase()

The `toUpperCase()` method returns the calling string value converted to uppercase

### Syntax

```javascript
toUpperCase()
```

```javascript
const sentence = 'The quick brown fox jumps over the lazy dog.';

console.log(sentence.toUpperCase());
// Expected output: "THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG."
```

# split()

The `split()` method splits a string into an array of substrings based on a specified delimiter.

### Syntax

```javascript
split(separator)
split(separator, limit)
```

```javascript
const str = 'The quick brown fox jumps over the lazy dog.';

const words = str.split(' ');
console.log(words[3]);
// Expected output: "fox"

const chars = str.split('');
console.log(chars[8]);
// Expected output: "k"

const strCopy = str.split();
console.log(strCopy);
// Expected output: Array ["The quick brown fox jumps over the lazy dog."]
```

# startsWith()

The `startsWith()` method determines whether a string begins with the characters of a specified string, returning `true` or `false` as appropriate.

### Syntax

```javascript
startsWith(searchString)
startsWith(searchString, position)
```

```javascript
const str1 = 'Saturday night plans';

console.log(str1.startsWith('Sat'));
// Expected output: true

console.log(str1.startsWith('Sat', 3));
// Expected output: false
```

# search()

The `search()` method executes a search for a match between a regular expression and this [`String`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String) object.

### Syntax

```javascript
search(regexp)
```

```javascript
const paragraph = 'The quick brown fox jumps over the lazy dog. If the dog barked, was it really lazy?';

// Any character that is not a word character or whitespace
const regex = /[^\w\s]/g;

console.log(paragraph.search(regex));
// Expected output: 43

console.log(paragraph[paragraph.search(regex)]);
// Expected output: "."
```

# replace()

The `replace()` method returns a new string with one, some, or all matches of a `pattern` replaced by a `replacement`. The `pattern` can be a string or a [`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp), and the `replacement` can be a string or a function called for each match. If `pattern` is a string, only the first occurrence will be replaced. The original string is left unchanged.

### Syntax

```javascript
replace(pattern, replacement)
```

```javascript
const p = 'The quick brown fox jumps over the lazy dog. If the dog reacted, was it really lazy?';

console.log(p.replace('dog', 'monkey')); // Expected output: "The quick brown fox jumps over the lazy monkey. If the dog reacted, was it really lazy?"

const regex = /Dog/i; console.log(p.replace(regex, 'ferret')); // Expected output: "The quick brown fox jumps over the lazy ferret. If the dog reacted, was it really lazy?"
```

# replaceAll()

The `replaceAll()` method returns a new string with all matches of a `pattern` replaced by a `replacement`. The `pattern` can be a string or a [`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp), and the `replacement` can be a string or a function to be called for each match. The original string is left unchanged.

### Syntax

```javascript
replaceAll(pattern, replacement)
```

```javascript
const p = 'The quick brown fox jumps over the lazy dog. If the dog reacted, was it really lazy?';

console.log(p.replaceAll('dog', 'monkey'));
// Expected output: "The quick brown fox jumps over the lazy monkey. If the monkey reacted, was it really lazy?"


// Global flag required when calling replaceAll with regex
const regex = /Dog/ig;
console.log(p.replaceAll(regex, 'ferret'));
// Expected output: "The quick brown fox jumps over the lazy ferret. If the ferret reacted, was it really lazy?"
```

# padStart()

The `padStart()` method pads the current string with another string (multiple times, if needed) until the resulting string reaches the given length. The padding is applied from the start of the current string.

### Syntax

```javascript
padStart(targetLength)
padStart(targetLength, padString)
```

```javascript
const str1 = '5';

console.log(str1.padStart(2, '0'));
// Expected output: "05"

const fullNumber = '2034399002125581';
const last4Digits = fullNumber.slice(-4);
const maskedNumber = last4Digits.padStart(fullNumber.length, '*');

console.log(maskedNumber);
// Expected output: "************5581"
```

# padEnd()

The `padEnd()` method pads the current string with a given string (repeated, if needed) so that the resulting string reaches a given length. The padding is applied from the end of the current string.

### Syntax

```javascript
padEnd(targetLength)
padEnd(targetLength, padString)
```

```javascript
const str1 = 'Breaded Mushrooms';

console.log(str1.padEnd(25, '.'));
// Expected output: "Breaded Mushrooms........"

const str2 = '200';

console.log(str2.padEnd(5));
// Expected output: "200  "
```

# match()

The `match()` method retrieves the result of matching a string against a regular expression.

### Syntax

```javascript
match(regexp)
```

```javascript
const paragraph = 'The quick brown fox jumps over the lazy dog. It barked.';
const regex = /[A-Z]/g;
const found = paragraph.match(regex);

console.log(found);
// Expected output: Array ["T", "I"]
```

# matchAll()

The `matchAll()` method returns an iterator of all results matching a string against a regular expression, including capturing groups.

### Syntax

```javascript
matchAll(regexp)
```

```javascript
const regexp = /t(e)(st(\d?))/g;
const str = 'test1test2';

const array = [...str.matchAll(regexp)];

console.log(array[0]);
// Expected output: Array ["test1", "e", "st1", "1"]

console.log(array[1]);
// Expected output: Array ["test2", "e", "st2", "2"]
```

# includes()

The `includes()` method performs a case-sensitive search to determine whether one string may be found within another string, returning `true` or `false` as appropriate.

### Syntax

```javascript
includes(searchString)
includes(searchString, position)
```

```javascript
const sentence = 'The quick brown fox jumps over the lazy dog.';

const word = 'fox';

console.log(`The word "${word}" ${sentence.includes(word) ? 'is' : 'is not'} in the sentence`);
// Expected output: "The word "fox" is in the sentence"
```

# indexOf()

The `indexOf()` method of [`String`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String) values searches this string and returns the index of the first occurrence of the specified substring. It takes an optional starting position and returns the first occurrence of the specified substring at an index greater than or equal to the specified number.

### Syntax

```javascript
indexOf(searchString)
indexOf(searchString, position)
```

```javascript
const paragraph = 'The quick brown fox jumps over the lazy dog. If the dog barked, was it really lazy?';

const searchTerm = 'dog';
const indexOfFirst = paragraph.indexOf(searchTerm);

console.log(`The index of the first "${searchTerm}" from the beginning is ${indexOfFirst}`);
// Expected output: "The index of the first "dog" from the beginning is 40"

console.log(`The index of the 2nd "${searchTerm}" is ${paragraph.indexOf(searchTerm, (indexOfFirst + 1))}`);
// Expected output: "The index of the 2nd "dog" is 52"
```

# charAt()

The `charAt()` method of [`String`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String) values returns a new string consisting of the single UTF-16 code unit located at the specified offset into the string.

### Syntax

```javascript
charAt(index)
```

```javascript
const sentence = 'The quick brown fox jumps over the lazy dog.';

const index = 4;

console.log(`The character at index ${index} is ${sentence.charAt(index)}`);
// Expected output: "The character at index 4 is q"
```

# concat()

The `concat()` method concatenates the string arguments to the calling string and returns a new string.

### Syntax

```javascript
concat(str1)
concat(str1, str2)
```

```javascript
const str1 = 'Hello';
const str2 = 'World';

console.log(str1.concat(' ', str2));
// Expected output: "Hello World"

console.log(str2.concat(', ', str1));
// Expected output: "World, Hello"
```

# endsWith()

The `endsWith()` method determines whether a string ends with the characters of a specified string, returning `true` or `false` as appropriate.

### Syntax

```javascript
endsWith(searchString)
endsWith(searchString, endPosition)
```

```javascript
const str1 = 'Cats are the best!';

console.log(str1.endsWith('best!'));
// Expected output: true

console.log(str1.endsWith('best', 17));
// Expected output: true

const str2 = 'Is this a question?';

console.log(str2.endsWith('question'));
// Expected output: false
```

# lastIndexOf()

The `lastIndexOf()` method of [`String`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String) values searches this string and returns the index of the last occurrence of the specified substring. It takes an optional starting position and returns the last occurrence of the specified substring at an index less than or equal to the specified number.

### Syntax

```javascript
lastIndexOf(searchString)
lastIndexOf(searchString, position)
```

```javascript
const paragraph = 'The quick brown fox jumps over the lazy dog. If the dog barked, was it really lazy?';

const searchTerm = 'dog';

console.log(`The index of the first "${searchTerm}" from the end is ${paragraph.lastIndexOf(searchTerm)}`);
// Expected output: "The index of the first "dog" from the end is 52"
```
