Make writing a habit together! This is the sixth day of my participation in the “Gold Digging Day New Plan · April More text Challenge”. Click here for more details. The String type in ES6 provides four handy new ways to write more readable code.

StartsWith () and endsWith ()

Let’s say we have a string,

Const name = ' ';Copy the code

We want to determine if the string starts with a front end

Name. StartsWith (' front-end ')Copy the code

Here we are using Chinese, but sometimes our data may be in English.

Const name = 'frontendpicker-pinxia ';Copy the code

To determine if it starts with front:

name.startsWith('front')
Copy the code

Let’s try uppercase letters, and we can see that StartWith is case-sensitive.

name.startsWith('Front')
Copy the code

In addition to this simplest usage, StartWith also supports skipping a certain number of characters for judgment.

Such as:

Const name = 'frontendpicker-pinxia '; name.startsWith('ont',2)Copy the code

Here startsWith skips two characters.

In daily life, we also often use the scene where the end is not certain characters, such as the id card is really the last bit.

So here we have a string

Const name = '123456 banxia 001';Copy the code

We want to determine whether the last three digits are 001 or not. Of course, we can still use startsWith, but we need to know the length of the string, which is quite troublesome.

Use endsWith directly.

name.endsWith('001')

Copy the code

If we want to decide whether to end with ‘Pinellia’, as startsWith can skip a specified number of characters. EndsWith can specify the first N characters as objects to be checked.

Name. The endsWith (' pinellia, 8)Copy the code

We can specify the first 8 characters as objects to be checked and ignore the rest!

.include()

.include() is mainly used to check that the package does not contain the specified string!

Const name = '123456 banxia 001';Copy the code

.repeat()

Repeat repeats the current string a specified number of times.

For example, we repeat 123 10 times.

'123'.repeat(10)
Copy the code

This repeat may be used in slightly fewer scenarios, but it can also be used for some strange needs.

For example, if you want to print three strings of different lengths at the terminal and want them to be right-aligned, what do you need to do?

First we need to make sure that the repeated string is a space, but the number of repetitions is not the same.

leftPad = function(str, length ){
    return `${' '.repeat(Math.max(length - str.length,0))}${str}`;
}
Copy the code