https://anuragdeep.com/

Photo by Lea L on Unsplash

String Methods in JavaScript: A Quick Reference Guide with Examples

Javascript Nov 11, 2022

Strings in JavaScript refer to any text data. Although it is a primitive type, the language allows you to manipulate it as if it were an object. Among other things, use the string methods included into JS, which are listed on this help sheet.

Important: when using methods, a new string is created, which is written to the same variable instead of the old string.


Photo by Bogomil Mihaylov on Unsplash

How to change case

toLowerCase

Converts characters in a string to lower case.

"Hello Anurag".toLowerCase(); // "hello anurag"

toUpperCase

Converts characters in a string to uppercase.

"Hello Anurag".toUpperCase(); // "HELLO ANURAG"

How to concatenate strings

concat

Concatenates two or more strings and returns a single string.

"Hello".concat(" Anurag"); // "Hello Anurag"
"Hello".concat(" A", "n", "u", "r", "a", "g"); // "Hello Anurag"

How to split a string into substrings

split

Splits a string into an array at the specified delimiter, which can be a substring or a regular expression. You can specify a limiter as the second parameter.

// Get each character
"Hello Anurag".split(""); // ["H", "e", "l", "l", "o", " ", "A", "n", "u", "r", "a", "g"]

// Getting each word from a string
"Hello Anurag".split(" "); //["Hello", "Anurag"]

// Using the limiter
"Hello Anurag".split(" ", 1); //["Hello"]

How to repeat a line

repeat

It takes a number as a parameter and repeats the string the specified number of times.

"Anurag ".repeat(3); // "Anurag Anurag Anurag "

How to find a substring

charAt

Returns the character at the specified index.

"Hello Anurag".charAt(); // "H"

includes

Checks if a string contains the specified substring. Returns true or false. As the second parameter, you can specify the position in the string from which to start the search.

"Hello Anurag".includes("Anurag"); // true
"Hello Anurag".includes("Hello", 1); // false

indexOf

Returns the index of the first occurrence of the specified value found. The search is carried out from the beginning to the end of the string. If there are no matches, it returns -1. As the second parameter, you can pass the position from which to start the search.

"Hello World".indexOf("o"); // 4
"Hello World".indexOf("o", 5); // 7

lastIndexOf

Returns the index of the last found occurrence of the specified value. The search is carried out from the end to the beginning of the string. If there are no matches, it returns -1. As the second parameter, you can pass the position from which to start the search.

"Hello World".lastIndexOf("o"); // 7
"Hello World".lastIndexOf("o", 5); // 4

endsWith

Checks if the string ends with the characters given by the first parameter. Returns true or false. There is a second optional parameter - a search range limiter. By default, it is equal to the length of the string.

"Hello Anurag".endsWith("Anurag"); // true
"Hello Anurag".endsWith("Anurag", 12); // false

startsWith

Checks if a string starts with the specified characters. Returns true or false. As the second parameter, you can specify the index from which to start the check.

"Hello Anurag".startsWith("Hello"); // true
"Hello Anurag".startsWith("Hello", 1); // false

Checks if a string contains the specified value or regular expression and returns the index of the start of the match.

"hi, hello, hey".search("hello"); // 4

How to extract a substring

slice

Extracts part of a string and returns a new string. The required parameter is the start of extraction. The second parameter can be used to set the border (by default - to the end of the line).

"String methods on Anurag".slice(18); // "Anuragd"
"String methods on Anurag".slice(18, 23); // "Anura"

// Negative values work too
"String methods on Anurag".slice(-6); // "Anurag"
"String methods on Anuragd".slice(-6, -2); // "Anur"

substring

Extracts characters from a string between two specified indexes. The second index is optional. In this case, all characters from the beginning to the end of the string will be extracted. Unlike slice, you can set start to be greater than end. Negative values ​​are not supported and are interpreted as 0.

"String methods on Anurag".substring(15, 7); // methods

substr

Extracts part of a string of the specified length. The first parameter takes the starting position, the second - the length. The value of the first parameter can be negative, in which case the position is determined from the end of the string.

"String methods on Anuragd".substr(7, 4); // "meth"
"String methods on Anuragd".substr(-6, 5); // "Anura"

How to replace a substring

replace

Searches a string for the specified value or regular expression and returns a new string that has been replaced with the second parameter. You can replace the found values ​​with another string, or pass a function to work on the matches.

"hi, hello, hi".replace("hi", "hey"); // "hey, hello, hi"
"hi, hello, hi".replace(/hi/g, "hey"); // "hey, hello, hey"

replaceAll

Gives the same result as the replace() method with the g global flag. Replaces all found matches with another string or the passed function.

"hi, hello, hi".replaceAll("hi", "hey"); // "hey, hello, hey"

How to add spaces or other characters to a string

padEnd

Adds indents at the end until the string reaches the length given by the first parameter. As the second parameter, you can specify another character instead of a space.

"Hello Anuragd".padEnd(20, "*"); // "Hello Anuragd*******"

padStart

Adds indents at the beginning until the string reaches the length given by the first parameter. As the second parameter, you can specify another character instead of a space.

"Hello Anurag".padStart(20, "*"); // "*******Hello Anurag"

How to remove spaces in a string

trim

Trims spaces from both ends of a string.

"   Hello Anurag ".trim(); // "Hello Anurag"

trimEnd

Trims spaces at the end of a string

"   Hello Anurag ".trimEnd(); // "   Hello Anurag"

trimStart

Trims spaces at the beginning of a line

"   Hello Anurag ".trimStart(); // "Hello Anurag "

How to work with Unicode

charCodeAt

Returns the Unicode numeric value at the specified index. Please note that upper and lower case letters have different codes.

"T".charCodeAt() // 84
"t".charCodeAt() // 116

fromCharCode

Converts Unicode numeric values ​​to readable characters.

String.fromCharCode(72, 101, 108, 108, 111); // "Hello"

Note : when working with emoji, rare mathematical symbols, hieroglyphs, you need to remember about surrogate pairs. These are characters that are written as two 16-bit words. The length of such strings is 2.

'?'.length; // 2, 

Surrogate pairs were not taken into account when generating JS, and the charCodeAt / fromCharCode string methods do not handle them correctly. The rare String.fromCodePoint and str.codePointAt methods that have recently appeared in the language work correctly with surrogate pairs.

To work with strings in JS, there are not only built-in methods, but also third-party libraries. They solve more complex problems. However, connecting them only makes sense if the built-in techniques' capabilities are indeed insufficient.


Tags

Anurag Deep

Logical by Mind, Creative by Heart