All JS String Methods In One Post!
Tags: javascript, webdev, typescript, beginners
Published: 2021-07-22 01:12:39

Hello everybody, I'm [Aya Bouchiha](https://t.me/AyaBouchiha), on this beautiful day we're going to discuss **all string methods** in 
**Javascript**!

Firstly, we need to know that all All methods do not change the original string, they return a new one.

## concat()

+ **concat()** : this method links together two strings or more.

```javascript
const firstName = 'Aya ';
const lastName = 'Bouchiha';
// 3 methods to concatenate two strings
console.log(firstName.concat(lastName)); // Aya Bouchiha
console.log(firstName +  lastName); // Aya Bouchiha
console.log(`${firstName}${lastName}`); // Aya Bouchiha
```

## match()

+ **match()**: used to searches a string for a match against a regular expression, and returns the matches as an Array.

```javascript
const quote =  "If you don't know where you are going, any road will get you there.";
console.log(quote.match(/you/g)) // [ "you", "you", "you" ]
```
## matchAll()

+ **matchAll()**: returns an iterator of all results matching a string against a regular expression, including capturing groups.
[more details...](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/matchAll)
```javascript
const conversation = `Hi, I'm Aya Bouchiha\nHello, I'm John Doe, nice to meet you.`;

const matchedArrays = [...conversation.matchAll(/I'm\s(?<firstName>[a-zA-Z]+)\s(?<lastName>[a-zA-Z]+)/gi)];

console.log(matchedArrays[0])

for (let matchedArray of matchedArrays) {
  const {firstName, lastName} = matchedArray['groups']
  console.log(firstName, lastName)
}
```

Output:
```javascript
[
  "I'm Aya Bouchiha",
  'Aya',
  'Bouchiha',
  index: 4,
  input: "Hi, I'm Aya Bouchiha\nHello, I'm John Doe, nice to meet you.",
  groups: [Object: null prototype] { firstName: 'Aya', lastName: 'Bouchiha' }
]

Aya Bouchiha
John Doe
```

## split()

+ **split(separator)** : convert a string to an array by splitting it into substrings.

```javascript
const allLetters = 'abcdefghijklmnopqrstuvwxyz'; 
console.log(allLetters.split())
console.log(allLetters.split(''))

const emails = 'developer.aya.b@gmail.com,johndoes@gmail.com,simon.dev@gmail.com';
console.log(emails.split(',')) 
```

Output:
```javascript
[ 'abcdefghijklmnopqrstuvwxyz' ]

[
  'a', 'b', 'c', 'd', 'e', 'f',
  'g', 'h', 'i', 'j', 'k', 'l',
  'm', 'n', 'o', 'p', 'q', 'r',
  's', 't', 'u', 'v', 'w', 'x',
  'y', 'z'
]

[
  'developer.aya.b@gmail.com',
  'johndoes@gmail.com',
  'simon.dev@gmail.com'
]
```

## replace()

+ **replace(searchString, newValue)**: is a method that returns a new string with some or all matches of a pattern replaced by a replacement. The pattern can be a **_string_** or a **_RegExp_**, and the replacement can be a string or a function to be called for each match. If a pattern is a **string**, only the **first** occurrence will be replaced.[more details](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace)

```javascript
const email = 'john.doe@gmail.com';
console.log(email.replace('@gmail.com', '')); // john.doe
console.log(email.replace(/@[a-z]+.[a-z]+/g, '')); // john.doe
```

## replaceAll()

+ **replaceAll(searchString, newValue)**: is a method that returns a new string with all matches of a pattern replaced by a replacement. The pattern can be a string or a RegExp, and the replacement can be a string or a function to be called for each match.[more details...](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replaceall)

```javascript
const slug = '5-html-tags-that-almost-nobody-knows';
// 5 html tags that almost nobody knows
console.log(slug.replaceAll('-', ' ')); 
// 5 html tags that almost nobody knows
console.log(slug.replaceAll(/-/g, ' ')); 
```

## search()

+ **search(valueToSearch)** : returns the position (*index*) of a specific value in a string, if the specific value does not exist in the string, it returns -1.

```javascript
const quote = 'A dream does not become reality through magic; it takes sweat, determination, and hard work';
console.log(quote.search('magic')); // 40
console.log(quote.search(/life/g)); // -1
```


## trim()

+ **trim()** : delete whitespaces & tabs from the start & the end of a string

```javascript
const inputValue = '  Aya   Bouchiha\t';
console.log(inputValue.trim()); // Aya   Bouchiha
```

## includes()

+ **includes(value)** : this method checks if a giving value exists in a string. if the value exists, It returns **_true_**, otherwise, It returns **_false_** 

```javascript
const address = 'Morocco, Rabat';
console.log(address.includes('Morocco'));// true
console.log(address.includes('morocco'));// false
console.log(address.includes('tanger')); // false
```

## toLowerCase()

+ **toLowerCase()** : this method returns a given string with lowercase letters.

```javascript
const name = 'AYa BoUCHIha';
console.log(name.toLowerCase()) // aya bouchiha
```


## toUpperCase()

+ **toUpperCase()** :  returns a given string with uppercase letters.

```javascript
const name = 'AYa BoUCHIha';
console.log(name.toUpperCase()) // AYA BOUCHIHA
```

## toLocaleUpperCase()

+ **toLocaleUpperCase(locals: *optional*)** : returns a given string with uppercase letters according to locale-specific case mappings. It's the same thing with **toLocaleLowerCase** but this one returns the string with lowercase letters. [more details](https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Global_Objects/String/toLocaleUpperCase)

```javascript
const turkishSentence = 'iskender kebap';
// ISKENDER KEBAP
console.log(turkishSentence.toLocaleUpperCase('en-us')); 
// İSKENDER KEBAP
console.log(turkishSentence.toLocaleUpperCase('tr')) 
```


## repeat()

+ **repeat(n)** : returns a string repeated *n* times.

```javascript
const firstName = 'aya';
console.log(firstName.repeat(3)) // ayaayaaya
```


## slice()

+ **slice(startIndex = 0, endIndex = str.length)** : is a string method that extract a specific part of a string. It is simillar to **substring**.[difference between slice and substring...](https://www.geeksforgeeks.org/javascript-difference-between-string-slice-and-string-substring/)

```javascript
const fullName = 'Aya Bouchiha';
console.log(fullName.slice()) // Aya Bouchiha
console.log(fullName.slice(0,3)) // Aya
console.log(fullName.slice(4,fullName.length)) // Bouchiha
```

## substr()

+ **substr(startIndex, length=string.length)** : returns a specific part of a string, starting at the specified index and extending for a given number of characters afterwards.

```javascript
const fullName = 'Aya Bouchiha';
console.log(fullName.substr(0,3)) // Aya
console.log(fullName.substr(4,8)) // Bouchiha
```

## chartAt()

+ **chartAt(index = 0)** : this method returns the character at a giving index in a string.
Note: `0 <= index < string.length`

```javascript
const product = 'laptop';
console.log(product.charAt(3)) // t
console.log(product.charAt(10)) // ''
product.charAt("this is a string!") // l
console.log(product.charAt()) // l
```

## charCodeAt()

+ **charCodeAt(index)**: method returns an integer between 0 and 65535 representing the UTF-16 code unit at the given index.

```javascript
const product = 'laptop';
console.log(`the character code of ${product.charAt(2)} is  ${product.charCodeAt(2)}`)
// the character code of p is 112
```

## startsWith()

+ **startsWith(valueToSearch, startingIndex = 0)** : returns **true** if a string starts with a giving value, otherwise It returns **false**;

```javascript
const phoneNumber = '+212612342187';
console.log(phoneNumber.startsWith('+212')) // true
console.log(phoneNumber.startsWith('6',4)) // true
console.log(phoneNumber.startsWith('6',3)) // false
```


## endsWith()

+ **endsWith(valueToSearch, length=string.length)** : returns **true** if a string ends with a giving value, otherwise It returns **false**;

```javascript
const address = 'tanger, Morocco';
console.log(address.endsWith('Morocco')); // true
console.log(address.endsWith('Canada')); // false

const gmail = 'developer.aya.b@gmail.com';
const isGmail = gmail.endsWith('@gmail', gmail.length - 4)
console.log(isGmail); // true
```


## fromCharCode()

+ **fromCharCode(n1, n2,...)** : converts a unicode number to a character.

```javascript
console.log(String.fromCharCode(112)) // p
console.log(String.fromCharCode(105,106)) // ij
```

## indexOf()

+ **indexOf(value, start=0)** : returns the position of the first occurrence of a specified value in a string. If the value is not found, It returns **-1**.

```javascript
const quote = "every day may not be good... but there's something good in every day";
console.log(quote.indexOf('good')); // 21
console.log(quote.indexOf('good',24)); // 51
```

## lastIndexOf()

+ **lastIndexOf(value, start)** : returns the position of the last occurrence of a specified value in a string. It searches the string from the end to the beginning, but returns the index s from the beginning, starting at position 0.
If the value is not found, It returns **-1**.


```javascript
const quote = "every day may not be good... but there's something good in every day";
console.log(quote.lastIndexOf('good')); // 51
console.log(quote.lastIndexOf('good',24)); // 21
```

## localeCompare()

+ **localeCompare(stringToCompare, locales)** :  returns *-1*, *1*, or *0* if the string comes *before*, *after*, or is *equal* the given string in sort order.[more details](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/localeCompare)

```javascript
const word1 = 'feel';
const word2 = 'flee';
// returns -1
// because word1 comes before word2
console.log(word1.localeCompare(word2)) 
```


## valueOf()

+ **valueOf()** : returns the primitive value of a string.

```javascript
const fName = new String('Aya');
const lName = 'Bouchiha';
console.log(fName); // [String: 'Aya']
console.log(fName.valueOf()); // Aya
console.log(lName.valueOf()); // Bouchiha
```


## toString()

+ **toString()** : returns a string representing the specified object.

```javascript
const moroccanCity = new String('tanger');
console.log(moroccanCity); // [String: 'tanger']
console.log(moroccanCity.toString()) // tanger
```

### Summary

+ **concat()** : links together two strings or more.
+ **match()** : searchs a string for a match against a regular expression, and returns the matches as an Array.
+ **matchAll()**:  returns an iterator of all results matching a string against a regular expression, including capturing groups.
+ **split()** : convert a string to an array by spliting it into substrings.
+ **replace()**, replaceAll() : return a new string with some or all matches of a pattern replaced by a replacement.
+ **search()** :returns the position of a specific value in a string
+ **trim()** :delete whitespaces & tabs from the start & the end of a string
+ **includes()** : checks if a giving value exists in a string
+ **toLowerCase()** : returns a given string with lowercase letters.
+ **toUpperCase()** : returns a given string with uppercase letters.
+ **toLocaleLowerCase()** : returns a given string with lowercase letters according to locale-specific case mappings.
+ **toLocaleUpperCase()** : returns a given string with uppercase letters according to locale-specific case mappings.
+ **repeat()** : repeat a string n times
+ **slice()**, **substr()**, **substring()** : extract a specific part of a string
+ **chartAt()** :returns the character at a giving index in a string.
+ **charCodeAt()** :returns an integer between 0 and 65535 representing the UTF-16 code unit at the given index.
+ **startsWith()** : returns **true** if a string starts with a giving value, otherwise It returns **false**;
+ **endsWith()** :returns **true** if a string ends with a giving value, otherwise It returns **false**;
+ **fromCharCode()** : converts a unicode number to a character.
+ **indexOf()** : returns the position of the first occurrence of a specified value in a string.
+ **toString()** : returns a string representing the specified object.
+ **lastIndexOf()** :eturns the position of the last occurrence of a specified value in a string.
+ **localeCompare()** :returns *-1*, *1*, or *0* if the string comes *before*, *after*, or is *equal*  the given string in sort order.
+ **valueOf()** : returns the primitive value of a string.

to contact me:
+ gmail: developer.aya.b@gmail.com
+ telegram: [AyaBouchiha](https://t.me/AyaBouchiha)

## References

-   [www.w3schools.com](https://www.w3schools.com/)
-   [www.developer.mozilla.org](https://developer.mozilla.org/en-US/)

Have an amazing day!