Categories
JavaScript JavaScript Basics

The Comprehensive List of JavaScript String Methods

Spread the love

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.


Static Methods

Static methods are called without having to create a string literal or object. There are the following methods:

String.fromCharCode()

With the fromCharCode method, we can construct a string by passing in a comma-separated list of HTML character codes or the hexadecimal Unicode character code as arguments and get a string with the actual characters returned. For example, we can write:

const str = String.fromCharCode(38, 8226)

Then, we get &• when we log str with console.log. We can pass in hexadecimal character codes, like in the following code:

const str = String.fromCharCode(0x0026, 0x2022)

Then, we also get &• when we log str with console.log.

String.fromCodePoint()

The String.fromCodePoint() method returns a string given by the character codes that you entered into the arguments. The code points can be HTML character codes or the hexadecimal Unicode character code. For example, we can write:

const str = String.fromCodePoint(38, 8226)

Then, we get &• when we log str with console.log. We can pass in hexadecimal character codes, like in the following code:

const str = String.fromCodePoint(0x0026, 0x2022)

Then, we also get &• when we log str with console.log.


Instance Methods

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.

String.prototype.charAt()

charAt returns the character located at the index of the string.

For example:

const str = "Hello";  
const res = str.charAt(0); // 'H'

String.charCodeAt()

charCodeAt returns the UTF-16 character code located at the index of the string.

For example:

const str = "Hello";  
const res = str.charCodeAt(0); // 72

String.prototype.codePointAt()

codePointAt returns the code point value of the UTF-16 encoded code point located at the index of the string.

For example:

const str = "Hello";  
const res = str.codePointAt(0); // 72

String.prototype.concat()

The concat method combines two strings and returns a new string. For example, we can write:

const str1 = "Hello";  
const str2 = " World";  
const res = str1.concat(str2); // 'Hello World'

String.prototype.endsWith()

endsWith checks if a string ends with the substring you passed in.

For example:

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

String.prototype.includes()

includes checks if the passed-in substring is in the string. It returns true if it’s in the string, and false otherwise.

const str = "Hello";  
const hasH = str.includes('H'); // true  
const hasW = str.includes('W'); // false

String.prototype.indexOf()

indexOf finds the index of the first occurrence of the substring. It returns -1 if not found.

For example:

const str = "Hello Hello.";  
const hasHello = str.indexOf("Hello"); // 0  
const hasHello2 = str.indexOf("abc"); // -1

String.lastIndexOf()

lastIndexOf finds the index of the last occurrence of the substring. It returns -1 if not found.

For example:

const str = "Hello Hello.";  
const hasHello = str.lastIndexOf("Hello"); // 6  
const hasHello2 = str.lastIndexOf("abc"); // -1

String.prototype.localeCompare()

The localeCompare method compares whether one string comes before another by using the locale’s rules for comparing the order of precedence of the string. The general syntax to call this method is:

referenceStr.localeCompare(compareString, locales, options)

It returns the following values depending on whether referenceStr comes before compareStr:

  • Negative when the referenceStr occurs before compareStr
  • Positive when the referenceStr occurs after compareStr
  • Returns 0 if they are equivalent

The first argument of the method is the string you want to compare with.

The second argument of the method optionally takes a locale string or an array of locale strings, which are BCP-47 language tag with optional Unicode extension keys. Unicode extension keys, including "big5han", "dict", "direct", "ducet", "gb2312", "phonebk", "phonetic", "pinyin", "reformed", "searchjl", "stroke", "trad", and "unihan" are also allowed in our locale strings. They specify the collations that we want to compare strings with. However, when there are fields in the options in the second argument that overlap with this, then the options in the argument overrides the Unicode extension keys specified in the first argument.

Numerical collations can be specified by adding kn to your locale string in your first argument. For example, if we want to compare numerical strings, then we can write:

console.log('10'.localeCompare('2', 'en-u-kn-true'));

Then, we get one since we specified kn in the locale string in the constructor. This makes the collator compare numbers, and 10 comes after two.

Also, we can specify whether upper or lowercase letters should be sorted first with the kf extension key. The possible options are upper, lower, or false. false means that the locale’s default will be the option. This option can be set in the locale string by adding it to the locale string as a Unicode extension key, and if both are provided then the option property will take precedence. For example, to make uppercase letters have precedence over lowercase letters, we can write:

console.log('Able'.localeCompare('able', 'en-ca-u-kf-upper'));

This will sort the same word with uppercase letters first. When we run console.log, we get -1 since we have an uppercase ‘A’ in ‘Able,’ and a lowercase ‘a’ for ‘able.’ On the other hand, if we instead pass in en-ca-u-kf-lower in the constructor, like in the code below:

console.log('Able'.localeCompare('able', 'en-ca-u-kf-lower'));

Then after console.log we get one because kf-lower means that we sort the same word with lowercase letters before the ones with uppercase letters.

The third argument of the method optionally takes an object that can have multiple properties. The properties that the object accepts are localeMatcher, usage, sensitivity, ignorePunctuation, numeric, and caseFirst. numeric is the same as the kn option in the Unicode extension key in the locale string, and caseFirst is the same as the kf option. The localeMatcher option specifies the locale matching algorithm to use. The possible values are lookup and best fit. The lookup algorithm searches for the locale until it finds the one that fits the character set of the strings that are being compared. best fit finds a locale that is possibly more suited than the lookup algorithm.

The usage option specifies whether the Collator is used for sorting or searching for strings. The default option is sort.

The sensitivity option specifies the way that the strings are compared. The possible options are base, accent, case, and variant. base compares the base of the letter, ignoring the accent. For example, a is not the same as b, but a is the same as á, and a is the same as Ä . accent specifies that a string is only different if their base letter or their accent is unequal, ignoring case. So, a isn’t the same as b, but a is the same as A. a is not the same as á.

The case option specifies that strings that are different in their base letters or case are considered unequal, and so a wouldn’t be the same as A and a wouldn’t be the same as c, but a is the same as á. variant means that strings that have different base letters, accents, other marks, or cases are considered unequal. For example, a wouldn’t be the same as A and a wouldn’t be the same as c, but a also wouldn’t be the same as á.

The ignorePunctuation specifies whether punctuation should be ignored when sorting strings. It’s a boolean property and the default value is false.

String.prototype.match()

The match method retrieves the substring matches of a string given the regular expression to match with. The match method takes a regular expression as an argument. It can either be a regular expression literal or a RegExp object. If no regular expression is given, we’ll get an array with an empty string. If the regular has the g flag, then all the matches in a string will be returned in the array. Otherwise, only the first will be returned.

The matches are returned as an array. For example, we can do a case insensitive search with the i flag:

const str = 'foo';  
const re = /foo/i;  
const found = str.match(re);  
console.log(found);

If we run the code above, we get:

[  
  "foo"  
]

from the console.log statement above.

If we toggle the g flag on and off, we get different results. If the regular has the g flag, then all the matches in a string will be returned in the array. Otherwise, only the first will be returned. If we have the g flag on like in the code below:

const str = 'The quick brown fox jumps over the lazy dog. It barked.';  
const globalRe = /[A-Z]/g;  
const globalFound = str.match(globalRe);  
console.log(globalFound);  
console.log(JSON.stringify(globalFound, (key, value) => value, 2));

Then we get:

[  
  "T",  
  "I"  
]

from the console.log statement above. However, if we removed the g flag, like in the code below:

const re = /[A-Z]/;  
const found = str.match(re);  
console.log(found);  
console.log(JSON.stringify(found, (key, value) => value, 2));

Then we get:

[  
  "T"  
]

from the console.log statement above.

String.prototype.matchAll()

The matchAll method would return all the results that are found by passing in a regular expression to the argument of the matchAll method. It returns an iterator with arrays of the result as the array entries. For example, if we have the following code to do a global search:

const str = 'The quick brown fox jumps over the lazy dog. It barked.';  
const globalRe = /[A-Z]/g;  
const globalFound = [...str.matchAll(globalRe)];  
console.log(globalFound);  
console.log(JSON.stringify(globalFound, (key, value) => value, 2));

Then we get:

[  
  [  
    "T"  
  ],  
  [  
    "I"  
  ]  
]

On the other hand, if we don’t have the global flag in the regular expression to do a global search, like in the following code:

const re = /[A-Z]/;  
const found = [...str.matchAll(re)];  
console.log(found);  
console.log(JSON.stringify(found, (key, value) => value, 2));

Then we get:

[  
  [  
    "T"  
  ]  
]

from the console.log statement above.

String.prototype.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:

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

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

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:

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:

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:

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

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

String.prototype.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:

'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.prototype.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:

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

String.prototype.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:

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

String.prototype.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:

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:

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:

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

String.prototype.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:

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.prototype.startsWith()

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

For example:

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

String.prototype.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:

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:

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:

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.prototype.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:

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

String.prototype.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:

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

<img alt="" class="t u v lu aj" src="https://miro.medium.com/max/1400/0*4SZwSC2Q8P8AoyXU" width="700" height="1050" srcSet="https://miro.medium.com/max/552/0*4SZwSC2Q8P8AoyXU 276w, https://miro.medium.com/max/1104/0*4SZwSC2Q8P8AoyXU 552w, https://miro.medium.com/max/1280/0*4SZwSC2Q8P8AoyXU 640w, https://miro.medium.com/max/1400/0*4SZwSC2Q8P8AoyXU 700w" sizes="700px" role="presentation"/>

Photo by Allef Vinicius on Unsplash

String.prototype.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:

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

String.prototype.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:

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:

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

String.prototype.toUpperCase()

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

For example:

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

String.prototype.trim()

Remove starting and ending white space from a string.

For example:

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

String.prototype.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:

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() :

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.prototype.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:

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:

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *