The only JavaScript "String" Guide you will Ever Need.
Tags: javascript, webdev, tutorial, beginners
Published: 2022-08-18 16:12:09

## Strings

Strings can be created as primitives, from string literals, or as objects, using the `String()` constructor:

```js
const string1 = "A string primitive";
const string2 = 'Also a string primitive';
const string3 = `Yet another string primitive`;

const string4 = new String("A String object");
```

String literals can be specified using single or double quotes, which are treated identically, or using the backtick character. This last form specifies a template literal: with this form you can interpolate expressions.

---

### Finding the length of a string


```js
const myStr = 'Hello World!';
console.log(myStr.length); // 12
```
---

### Retrieving a specific string character

```js
const myStr = 'Hello World!';
console.log(myStr[2]); // l
```

> **Remember**: computers count from 0, not 1!

To retrieve the last character of _any_ string, we could use the following line, combining this technique with the `length` property we looked at above:

```js
const myStr = "Hello World!";
console.log(myStr[myStr.length - 1]); // !
```

---

## Static methods

### String.fromCharCode()

Returns a string created by using the specified sequence of Unicode values

**Syntax** - 
```js
String.fromCharCode(num1)
String.fromCharCode(num1, num2)
String.fromCharCode(num1, num2, /* …, */ numN)
```

Parameters -
A sequence of numbers that are UTF-16 code units. The range is between `0` and `65535` (`0xFFFF`). Numbers greater than `0xFFFF` are truncated. No validity checks are performed.

This method returns a `string` and not a String object.

**Example** -
```js
console.log(String.fromCharCode(72, 69, 76, 76,79)); // "HELLO"
```

---

### String.raw()

Returns a string created from a raw template string.

```js
// Create a variable that uses a Windows
// path without escaping the backslashes:
const filePath = String.raw`C:\Users\vedan\Desktop\index.js`;

console.log(`The file was uploaded from: ${filePath}`);
// Output - The file was uploaded from: C:\Users\vedan\Desktop\index.js
```

---

## Instance methods

### String.at()

Returns the character (exactly one UTF-16 code unit) at the specified `index`. Accepts negative integers, which count back from the last string character.

```js
const myStr = "Hello world!";
console.log(myStr.at(4)); // o
console.log(myStr.at(-2)); // d
```

---

### String..charAt()

Same as `String.at()` but charAt() does not accept negative index.

```js
const myStr = "Hello world!";
console.log(myStr.charAt(4)); // o
console.log(myStr.charAt(-2)); // 
```

If Negative index is provided it does not return anything.

---

### String.charCodeAt(index)

Returns a number that is the UTF-16 code unit value at the given `index`.

If `index` is out of range, `charCodeAt()` returns `NaN`.

```js
const myStr = "Hello world!";

console.log(
  `The character code ${myStr.charCodeAt(2)} is equal to ${myStr.charAt(2)}`
);

// Output - The character code 108 is equal to l
```

---

### String.concat()

The `concat()` function concatenates the string arguments to the calling string and returns a new string. Changes to the original string or the returned string don't affect the other.

If the arguments are not of the type string, they are converted to string values before concatenating.

```js
const myStr = "Hello world";
const concatStr = "".concat("My ", 1, "st ", myStr, " Program!");
console.log(concatStr); // My 1st Hello world Program!
```

---

### String.includes()

This method lets you determine whether or not a string includes another string.The `includes()` method is case sensitive.

```js
const myStr = "Hello world";
console.log(myStr.includes("Hello")); // true
console.log(myStr.includes("hello")); // false
```

---

### String.startsWith(searchString,position)

This method lets you determine whether or not a string begins with another string. This method is case-sensitive.

It also takes a optional argument `position`
The position in this string at which to begin searching for `searchString`. Defaults to `0`.

```js
const myStr = "Hello world";
console.log(myStr.startsWith("Hello")); // true
```

---

### String.endsWith(searchString,position)

This method lets you determine whether or not a string ends with another string. This method is case-sensitive.

```js
const myStr = "Hello world";
console.log(myStr.endsWith("world")); // true
```

---

### String.indexOf()

The **`indexOf()`** method, given one argument: a substring to search for, searches the entire calling string, and returns the index of the first occurrence of the specified substring. Given a second argument: a number, the method returns the first occurrence of the specified substring at an index greater than or equal to the specified number.


```js
const sentence = "Hi! I am Vedant. I like to code.";

let firstOccurrence = sentence.indexOf("I");
let secondOccurrence = sentence.indexOf("I", firstOccurrence + 1);

console.log(
  `First Occurrence: ${firstOccurrence} , second Occurrence: ${secondOccurrence}`
);

// First Occurrence: 4 , second Occurrence: 17
```

---

### String.lastIndexOf()

The **`lastIndexOf()`** method, given one argument: a substring to search for, searches the entire calling string, and returns the index of the last occurrence of the specified substring. Given a second argument: a number, the method returns the last occurrence of the specified substring at an index less than or equal to the specified number.

```js
const sentence = "Hi! I am Vedant. I like to code.";
console.log(sentence.lastIndexOf("I")); // 17
```

---

### String.match()

Used to match regular expression `regexp` against a string.
Regular expressions are patterns used to match character combinations in strings. In JavaScript, regular expressions are also objects.

```js
const paragraph =
  "Cucumbers, spinach, broccoli and onions are considered non-starchy Vegetables.";
const regex = /[A-Z]/g; 
// This regex is used to match all Capital Case Alphabet characters Globally.
const found = paragraph.match(regex);

console.log(found); // [ 'C', 'V' ]
```

---

### String.normalize()

Unicode assigns a unique numerical value, called a _code point_, to each character. For example, the code point for `"A"` is given as U+0041. However, sometimes more than one code point, or sequence of code points, can represent the same abstract character — the character `"ñ"` for example can be represented by either of:

-   The single code point U+00F1.
-   The code point for `"n"` (U+006E) followed by the code point for the combining tilde (U+0303).

```js
const string1 = '\u00F1';
const string2 = '\u006E\u0303';

console.log(string1);  //  ñ
console.log(string2);  //  ñ
```

However, since the code points are different, string comparison will not treat them as equal. And since the number of code points in each version is different, they even have different lengths.

```js
const string1 = '\u00F1';            // ñ
const string2 = '\u006E\u0303';      // ñ

console.log(string1 === string2); // false
console.log(string1.length);      // 1
console.log(string2.length);      // 2
```

The `normalize()` method helps solve this problem by converting a string into a normalized form common for all sequences of code points that represent the same characters.

The function takes one argument `form` which is one of `"NFC"`, `"NFD"`, `"NFKC"`, or `"NFKD"`, specifying the Unicode Normalization Form. If omitted or `undefined`, `"NFC"` is used.

```js
const string1 = "\u00F1"; // ñ
const string2 = "\u006E\u0303"; // ñ

console.log(string1 === string2); // false

const normalizedString1 = string1.normalize("NFD");
const normalizedString2 = string2.normalize("NFD");

console.log(normalizedString1 === normalizedString2); // true
```

---

### String.padEnd(targetLength [, padString])

Pads the current string from the end with a given string and returns a new string of the length `targetLength`.

#### Parameters

**targetLength** -

The length of the resulting string once the current `str` has been padded. If the value is lower than `str.length`, the current string will be returned as-is.

**padString** -

The string to pad the current `str` with. The default value for this parameter is " " (`U+0020`).

```js
const myStr = "Hello World";
console.log(myStr.padEnd(14,"!")); // Hello World!!!
```

---

### String.padStart(targetLength [, padString])

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.

This also takes two arguments `targetLength` and `padString` same as String.padEnd().

```js
const cardNumber = "4535901040373156";
const last4Digits = cardNumber.slice(-4);
console.log(last4Digits.padStart(16,"*")); // ************3156
```

---

### String.repeat()

Returns a string consisting of the elements of the object repeated `count` times.

```js
const myStr = "Hello ";
console.log(myStr.repeat(3)); // Hello Hello Hello
```

---

### String.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`, 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.

```js
const sentence = "How much wood would a woodchuck chuck if a woodchuck could chuck wood?";

console.log(sentence.replace("wood","water"));

// How much water would a woodchuck chuck if a woodchuck could chuck wood?
```

---

### String.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`, and the `replacement` can be a string or a function to be called for each match. The original string is left unchanged.

```js
const sentence = "How much wood would a woodchuck chuck if a woodchuck could chuck wood?";

console.log(sentence.replaceAll("wood", "water"));

// How much water would a waterchuck chuck if a waterchuck could chuck water?
```

---

### String.search()

The **`search()`** method executes a search for a match between a regular expression and this `String` object.

```js
const myStr = "Hello World!"

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

console.log(myStr.search(regex));         // 11
console.log(myStr[myStr.search(regex)]);  // !
```

---

### String.slice(indexStart, indexEnd)

`slice()` extracts the text from one string and returns a new string. Changes to the text in one string do not affect the other string.

`slice()` extracts up to but not including `indexEnd`. For example, `str.slice(1, 4)` extracts the second character through the fourth character (characters indexed `1`, `2`, and `3`).

If `indexEnd` is not specified then it goes till end of the string.

```js
const myStr = "Hello World!";

console.log(myStr.slice(6)); // World!
```

---

### String.split()

The **`split()`** method takes a pattern and divides a `String` into an ordered list of substrings by searching for the pattern, puts these substrings into an array, and returns the array.

It takes two optional parameters-
1. `separator` - The pattern describing where each split should occur.
2. `limit` - A non-negative integer specifying a limit on the number of substrings to be included in the array. If provided, splits the string at each occurrence of the specified `separator`, but stops when `limit` entries have been placed in the array. Any leftover text is not included in the array at all.

```js
const myStr = "Hi, I am Vedant";

console.log(myStr.split()); // [ 'Hi, I am Vedant' ]
console.log(myStr.split(" ")); // [ 'Hi,', 'I', 'am', 'Vedant' ]
console.log(myStr.split(" ", 2)); // [ 'Hi,', 'I' ]
```

---

### String.substring()

The **`substring()`** method returns the part of the `string` between the start and end indexes, or to the end of the string.

```js
const myStr = "Hello World!";

console.log(myStr.substring(6, 11)); // World
```

---

### String.toLowerCase()

The `toLowerCase()` method returns the value of the string converted to lower case. `toLowerCase()` does not affect the value of the string `str` itself.

```js
const myStr = "HelLo WoRld!";

console.log(myStr.toLowerCase()); // hello world!
```

---

### String.toUpperCase()

The `toUpperCase()` method returns the value of the string converted to uppercase. This method does not affect the value of the string itself since JavaScript strings are immutable.

```js
const myStr = "HelLo WoRld!";

console.log(myStr.toUpperCase()); // HELLO WORLD!

```

---

### String.toString()

The **`toString()`** method of a string object returns a string representing the specified string.

```js
const myStr = new String("Hello World");

console.log(myStr); // [String: 'Hello World']
console.log(myStr.toString()); // Hello World
```

---

### String.trim()

The **`trim()`** method removes whitespace from both ends of a string and returns a new string, without modifying the original string. Whitespace in this context is all the whitespace characters (space, tab, no-break space, etc.) and all the line terminator characters (LF, CR, etc.).

```js
const myStr = "  Hello World ";

console.log(myStr.trim()); // "Hello World"
```

---

### String.trimStart()

The **`trimStart()`** method removes whitespace from the beginning of a string. `trimLeft()` is an alias of this method.

```js
const myStr = "  Hello World ";

console.log(myStr.trimStart()); // "Hello World "
```

---

### String.trimEnd()

The **`trimEnd()`** method removes whitespace from the end of a string. `trimRight()` is an alias of this method.

```js
const myStr = "  Hello World ";

console.log(myStr.trimEnd()); // "  Hello World"
```

---

### String.valueOf()

The **`valueOf()`** method returns the primitive value of a `String` object.

```js
const myStr = new String("Hello World");

console.log(myStr); // [String: 'Hello World']
console.log(myStr.valueOf()); // Hello World
```

---
---