Some Useful JavaScript String Methods You May Not Know About
Tags: javascript, beginners, tutorial, webdev
Published: 2020-01-06 02:54:30

**Subscribe to my email list now at http://jauyeung.net/subscribe/**

**Follow me on Twitter at https://twitter.com/AuMayeung**

**Many more articles at https://medium.com/@hohanga**

Strings are an important global object in JavaScript. They represent a sequence of characters. They can be used by various operators, like comparison operators, and there are various methods that can be used to manipulate them. There are different ways to manipulate strings, look up parts of a string in various positions, and trim and replace strings. With each release of the JavaScript specification, more methods are added to make string search and manipulating easier than ever.

Instance Methods Continued
==========================

Instance methods of a string are called on the string literal or the string object. They do something to the instance of the string that’s being called on. We continue the list from part 1.

String.normalize()
------------------

The `normalize` method returns the Unicode Normalization Form of a given string. It will convert non-string arguments into a string before conversion. For example, if we have:

```javascript
const first = '\\u00e5'; // "å"  
const second = '\\u0061\\u030A'; // "å"
```

Then we call the `normalize` method in each string to normalize them into the same character code:

```javascript
first.normalize('NFC') === second.normalize('NFC')
```

The code above will evaluate to `true` since we normalized the strings to the same character code. However, if we didn’t call `normalize`:

```javascript
first === second
```

Then the code above would return `false` . If we run `console.log` on both strings to get their character codes like in the code below:

```javascript
console.log(first.normalize('NFC').charCodeAt(0));  
console.log(second.normalize('NFC').charCodeAt(0));
```

We get 229 for the first characters for both strings since they’re the same after normalization. On the other hand, if we run it before normalization with `normalize` like in the code below:

```javascript
console.log(first.charCodeAt(0));  
console.log(second.charCodeAt(0));
```

We get that the first string logs 229 and the second logs 97.

String.padStart()
-----------------

The `padStart()` function 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.

The function takes 2 parameters. The first is the target length of your string. If the target length is less than the length of your string, then the string is returned as-is. The second parameter is the string that you want to add the padding with. It’s an optional parameter and it defaults to `' '` if nothing is specified.

For example, we can write the following:

```javascript
'def'.padStart(10);         // "       def"  
'def'.padStart(10, "123");  // "1231231def"  
'def'.padStart(6,"123465"); // "abcdef"  
'def'.padStart(8, "0");     // "00000def"  
'def'.padStart(1);          // "def"
```

Note that each string is filled up to the target length with the string in the second argument. The whole string in the second argument may not always be included. Only the part that lets the function fills the string up to the target length is included.

String.padEnd()
---------------

The `padEnd()` function 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 end of the current string.

The function takes 2 parameters. The first is the target length of your string. If the target length is less than the length of your string, then the string is returned as-is. The second parameter is the string that you want to add the padding with. It’s an optional parameter and it defaults to `' '` if nothing is specified.

For example, we can write the following:

```javascript
'def'.padEnd(10);         // "def       "  
'def'.padEnd(10, "123");  // "def1231231"  
'def'.padEnd(6,"123465"); // "defabc"  
'def'.padEnd(8, "0");     // "def00000"  
'def'.padEnd(1);          // "def"
```

String.repeat()
---------------

To use the `repeat` function, you pass in the number of times you want to repeat the string as an argument. It returns a new string.

For example:

```javascript
const hello = "hello";  
const hello5 = hello.repeat(5);  
console.log(hello5); // "hellohellohellohellohello"
```

String.replace()
----------------

The `replace()` function included with strings is useful for replacing parts of strings with another. It returns a new string with the string after the substring is replaced.

Example:

```javascript
const str = "Hello Bob";  
const res = str.replace("Bob", "James"); // 'Hello James'
```

`replace()` can also be used to replace all occurrences of a substring.

For example:

```javascript
const str = "There are 2 chickens in fridge. I will eat chickens today.";  
const res = str.replace(/chickens/g, "ducks"); // "There are 2 chickens in fridge. I will eat chickens today."
```

If the first argument is a regular expression that searches globally, it will replace all occurrences of the substring.

String.search()
---------------

`search` gets the position of the substring passed into the function. It returns -1 if the substring is not found in the string.

Example:

```javascript
const str = "Hello";  
const res = str.search('H'); // 0
```

String.slice()
--------------

The `slice` method extracts a part of the string and returns a new string. We can pass in both positive and negative numbers. If the range is positive, then the returned substring will start and end with the indexes that are passed in. If they’re negative, then the starting index starts from the last character of the string with index -1 and then count backward back to the start of the string, going down by 1 when a character is left of another character. If the second argument is omitted, then it’s assumed to be the index of the last character of the string.

For example, we can write:

```javascript
const str = 'Try not to become a man of success. Rather become a man of value.';  
console.log(str.slice(31));  
// output: "ess. Rather become a man of value."

console.log(str.slice(4, 19));  
// output: "not to become a"console.log(str.slice(-4));  
// output: "lue."console.log(str.slice(-9, -5));  
// output: "of v"
```

String.startsWith()
-------------------

`startsWith` checks if a string starts with the substring you pass in.

For example:

```javascript
const str = "Hello world.";  
const hasHello = str.startsWith("Hello"); // trueconst str2 = "Hello world.";  
const hasHello2 = str.startsWith("abc"); // false
```

String.split()
--------------

The `split` method splits a string into an array of substrings. The `split` method can split a string using a regular expression as the delimiter. For example, we can write:

```javascript
const str = 'The 1 quick 2 brown fox jump.';  
const splitStr = str.split(/(\\d)/);console.log(splitStr);   
// gets ["The ", "1", " quick ", "2", " brown fox jump."]
```

This splits a sentence into an array of strings with the numbers separating the words. It can also take a string as the delimiter for separating the string like in the following example:

```javascript
const str = 'The 1 quick 2 brown fox jump.';  
const splitStr = str.split(' ');console.log(splitStr);  
// gets ["The", "1", "quick", "2", "brown", "fox", "jump."]
```

It can also take an array of strings as separators of the given string instance. For example:

```javascript
const str = 'The 1 quick 2 brown fox jump.';  
const splitStr = str.split([' ']);  
console.log(splitStr);  
// gets ["The", "1", "quick", "2", "brown", "fox", "jump."]
```

String.substr()
---------------

JavaScript strings have a `substr` function to get the substring of a string.

It takes a starting index as the first argument and a number of characters from the start index, and so on as the second argument.

It can be used like this:

```javascript
const str = "Hello Bob";  
const res = str.substr(1, 4); // ello
```

String.substring()
------------------

JavaScript strings also has a `substring` function that takes the start and end index as two arguments and returns a string with the ones between the start and end indices.

The start index is included but the end index is excluded.

Example:

```javascript
const str = "Hello Bob";  
const res = str.substring(1, 3); // el
```


String.toLocaleLowerCase()
--------------------------

Converts a string to lowercase, according to the locale of your browser. The new string is returned instead of modifying the original string.

For example:

```javascript
const str = "Hello Bob!";  
const res = str.toLocaleLowerCase(); // hello bob!
```

String.toLocaleUpperCase()
--------------------------

Converts a string to uppercase, according to the locale of your browser. The new string is returned instead of modifying the original string.

For example:

```javascript
const str = "Hello Bob!";  
const res = str.toLocaleUpperCase(); // 'HELLO BOB!'
```

String.toLowerCase()
--------------------

Converts a string to lowercase. The new string is returned instead of modifying the original string.

For example:

```javascript
const str = "Hello Bob!";  
const res = str.toLocaleLowerCase(); // 'hello bob!'
```

String.toUpperCase()
--------------------

Converts a string to uppercase. The new string is returned instead of modifying the original string.

For example:

```javascript
const str = "Hello Bob!";  
const res = str.toLocaleUpperCase(); // 'HELLO BOB!'
```

String.trim()
-------------

Remove starting and ending white space from a string.

For example:

```javascript
const str = "         Hello Bob!     ";  
const res = str.trim(); // 'Hello Bob!'
```

String.trimStart()
------------------

Now the string object has a `trimStart()` function to trim the beginning whitespace of a string. There’s also a `trimLeft()` method which is an alias to this method.

For example, we can write:

```javascript
let message = '   Hi! How\'s it going?   ';
console.log(message);// We get '   Hi! How's it going?   'let message = '   Hi! How\\'s it going?   ';  
console.log(message.trimStart());// We get 'Hi! How's it going?   '
```

As we can see, the whitespace on the left side is gone. We can do the same thing with `trimLeft()` :

```javascript
let message = '   Hi! How\\'s it going?   ';  
console.log(message.trimLeft());// We get 'Hi! How's it going?   '
```

Note that a new string is returned with `trimStart` or `trimLeft`, so the original string stays intact. This prevents us from mutating the original string, which is handy for preventing mistakes from accidentally mutating objects.

String.trimEnd()
----------------

The `trimEnd` method removes whitespace from the right end of the string. `trimRight` is an alias of the `trimEnd` method. For example, we write:

```javascript
let message = '   Hi! How\'s it going?   ';  
console.log(message);  
// We get '   Hi! How's it going?   '

let message = '   Hi! How\'s it going?';  
console.log(message.trimEnd());  
// We get '   Hi! How's it going?'
```

Note that a new string is returned with `trimEnd` or `trimRight`, so the original string stays intact. This prevents us from mutating the original string, which is handy for preventing mistakes from accidentally mutating objects.

String.valueOf()
----------------

With the `valueOf` method, we can convert a string object into a primitive string. For example, we can write:

```javascript
const sPrim = 'foo';  
const sObj = new String(sPrim);  
console.log(typeof sPrim);  
console.log(typeof sObj.valueOf());
```

Then we get that both `console.log` statements would show ‘string’.

Conclusion
----------

Strings are an important global object in JavaScript. It represents a sequence of characters. It has methods to manipulate strings, look up parts of a string in various positions, and trim and replace strings. With each release of the JavaScript specification, more methods are added to make string search and manipulating easier than ever.