JavaScript Strings

To create strings, we can both directly assign a string to a variable or constant:

const name = "Tom";

The String object is meant to work with strings , so you can also use the String constructor:

const name = new String("Tom");

But as a rule, the first shorter method is used. In the first case, JavaScript automatically converts the primitive type variable into a String object if necessary.

The String object has a large set of properties and methods with which we can manipulate strings.

Line length

The length property indicates the length of the string:

const hello = "hello world";
console.log(`In the string "${hello}" ${hello.length} characters`);
// There are 10 characters in the string "hello world"

Line repetition

The repeat() method allows you to create a string by repeating another string multiple times. The number of repetitions is passed as an argument:

const hello = "hello";
console.log(hello.repeat(3)); // hello hello hello

Search in a string

To search for some substring in a string, the indexOf() (index of the first occurrence of the substring) and lastIndexOf() (index of the last occurrence of the substring) methods are used. These methods take two parameters:

substring to find

An optional parameter that specifies from which characters to search for a substring in the string

Both of these methods return the index of the character at which the substring begins in the string. If the substring is not found, then -1 is returned.

const hello = "hello world. bye world";
const key = "world";
const firstPos = hello.indexOf(key);
const lastPos = hello.lastIndexOf(key);
console.log("First occurrence: ", firstPos); // 7
console.log("Last occurrence: ", lastPos); // 17

Another method includes() returns true if the string contains a specific substring.

const hello = "hello world. bye world";

console.log(hello.includes("world")); // true
console.log(hello.includes("moment")); // false

Using the second additional parameter, you can specify the index from which the search for the substring will begin:

const hello = "hello world. bye world";

console.log(hello.includes("world", 5)); // true
console.log(hello.includes("hello", 6)); // false

Substring selection

To cut a substring from a string, the substring() and slice() methods are used.

Substring

The substring() method takes two parameters:

The index of the character in the string from which to trim the string. Required parameter

the index to which the string should be trimmed. Optional parameter – if it is not specified, then the rest of the string is truncated

const hello = "hello world. bye world";
const world = hello.substring(7, 10); // from 7th to 10th index
console log(world); // world
const bye = hello.substring(12); // from index 12 to end of string
console log(bye); // while the world

slice

Another slice method also allows you to get some part of a string from it. It takes two parameters:

The index of the character in the string from which to trim the string. Required parameter

the index to which the string should be trimmed. Optional parameter – if it is not specified, then the rest of the string is truncated

const hello = "hello world. bye world";
const world = hello slice(7, 10); // from 7th to 10th index
console log(world); // world
const bye = hello slice(12); // from index 12 to end of string
console log(bye); // while the world

You can see that this method is similar to the method substring(), however, there are slight differences between them. First of all, the slice()start index must be less than the end index. In substring(), if the start index is greater than the end index, then they are swapped (that is, it substring(5, 1)will be equivalent substring(1, 5)):

const hello = "hello world. bye world";
const world1 = hello slice(6, 0); //
console log(world1); //
const world2 = hello.substring(6, 0); // similar to hello.substring(0, 6)
console log(world2); // Hey

Another difference is that it slice allows the use of negative indices. A negative index indicates the character index relative to the end of the string. substring()negative indexes are not supported:

const hello = "hello world. bye world";
const bye1 = hello slice(-8, -4); // from the 8th index from the end to the 4th index from the end
console log(bye1); //
const bye2 = hello.substring(-8, -4); // does not work
console log(bye2); //

Register management

To change the case, there are methods toLowerCase() (for converting to lower case) and toUpperCase() (for converting to upper case).

const hello = "Hello Tom";
console.log(hello.toLowerCase()); // Hi Tom
console.log(hello.toUpperCase()); // HI TOM

Getting a character by index

To get a specific character in a string by index, you can use the charAt() and charCodeAt() methods . Both of these methods take a character index as a parameter:

const hello = "Hello Tom";
console.log(hello.charAt(2)); // and
console.log(hello.charCodeAt(2)); // 1080

But if the method charAt()returns the character itself as a result, then the method charCodeAt()returns the numeric code of that character.

Removing spaces

To remove leading and trailing spaces in a string, use the trim() method :

let hello = " Hello Tom ";
const beforeLength = hello.length;
hello = hello.trim();
const afterLength = hello.length;
console.log("Line length until: ", beforeLength); // 15
console.log("Length of lines after: ", afterLength); // 10
  • Additionally, there are a number of methods that remove spaces from a specific side of a string:
  • trimStart() : removes a space from the beginning of a string
  • trimEnd() : removes whitespace from the end of a string
  • trimLeft() : removes whitespace from the left side of a string
  • trimRight() : removes whitespace from the right side of a string

String Concatenation

The concat() method concatenates two strings:

let hello = "hello";
let world = "world";
hello = hello.concat(world);
console log(hello); // Hello World

Substring replacement

The replace() method replaces the first occurrence of one substring with another:

let hello = "Good afternoon";
hello = hello.replace("day", "evening");
console log(hello); // Good evening

The first parameter of the method specifies which substring to replace, and the second parameter to which substring to replace.

At the same time, this method has one peculiarity – it replaces only the first occurrence of a substring:

let menu = "Breakfast: porridge, tea. Lunch: soup, tea. Dinner: salad, tea.";
menu = menu.replace("tea", "coffee");
console log(menu); // Breakfast: porridge, coffee. Lunch: soup, tea. Dinner: salad, tea.

However, another method – replaceAll() allows you to replace all occurrences of a substring:

let menu = "Breakfast: porridge, tea. Lunch: soup, tea. Dinner: salad, tea.";
menu = menu.replaceAll("tea", "coffee");
console log(menu); // Breakfast: porridge, coffee. Lunch: soup, coffee. Dinner: salad, coffee.

Splitting a string

The split() method splits a string into an array of substrings at a specified delimiter. The separator is a string that is passed to the method:

const message = "The weather was beautiful today";
const messageParts = message.split(" ");
console.log(messageParts); // ["Today", "was", "beautiful", "weather"]

In this case, the string is split by problem, so the message Parts array will end up with four elements.

Checking the beginning and end of a string

The startsWith() method returns true if the string starts with a specific substring. And the endsWith() method returns true if the string ends with a certain substring.

const hello = "let me speak from my heart";
console.log(hello.startsWith("let"));       // true
console.log(hello.startsWith("Let"));       // false
console.log(hello.startsWith("lets"));      // false

console.log(hello.endsWith("heart"));       // true
console.log(hello.startsWith("bart"));      // false

In this case, the case of characters plays a role, and from the example, above we see that “let” is not equivalent to “Let”.

An optional second parameter allows you to specify the index (for startsWith – the index from the beginning, and for endsWith – the index from the end of the string) against which the comparison will be made:

const hello = "let me speak from my heart";
console.log(hello.startsWith("me", 4));     // true, "me" - 4 index from the beginning of the string

console.log(hello.startsWith("my", hello.length-8));    // true, "my" - 8 index from the end

String completion

The padStart () and padEnd() methods stretch the string for a certain number of characters and fill the string to the left and right, respectively.

let hello = "hello".padStart(8);  // "   hello"
console.log(hello);
hello = "hello".padEnd(8);      // "hello   "
console.log(hello);

The call “hello”.padStart(8)will stretch the string “hello” by 8 characters. That is, initially there are 5 characters in the string “hello”, which means that 3 characters will be added to it. At what they will be added at the beginning of the line. By default, the added characters represent spaces. Similarly, the call “hello”.padEnd(8)will stretch the string by 8 characters, but the remaining characters as spaces will be added to the end of the string.

By default, these methods use spaces for padding, but as a second parameter, we can pass a value to the methods to pad the string with:

let hello = "hello".padStart(17, "JavaScript, ");  // "JavaScript, hello"
hello = "hello".padEnd(12, " Eugene");      // "hello Eugene"

If the added number of characters is greater than the added string, then the added string is repeated:

let hello = "123".padStart(6, "0"); // "000123"
hello = "123".padEnd(6, "0"); // "123000"