4 String Methods in ES6

Get into the habit of writing together! This is the sixth day of my participation in the "Nuggets Daily New Plan · April Update Challenge", click to view the details of the event . The String type in ES6 provides four very handy new methods that help us write more readable code.

.startsWith() 和 .endsWith()

For example we have a string,

const name = '搞前端的半夏';

复制代码

We want to determine if this string 搞前端starts with

name.startsWith('搞前端')

复制代码

image-20220124214627964

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

const name = 'frontendpicker-半夏';
复制代码

Want to judge whether it starts with front:

name.startsWith('front')
复制代码

image-20220124214935092

Let's try capital letters, we can find that startwith is case sensitive.

name.startsWith('Front')
复制代码

image-20220124215150786

In addition to this simplest usage, startwith also supports skipping a certain number of characters to judge.

E.g:

const name = 'frontendpicker-半夏';
name.startsWith('ont',2)
复制代码

Here startsWith skips two characters directly.

image-20220124215551413

In daily life, we also often use the scene where the end is not a certain character, for example, the ID card is really the last digit.

Below we have a string

const name = '123456半夏001';
复制代码

We want to determine whether the last three digits are 001. Of course, we can still use startsWith, but this also needs to know the length of the string, which is more troublesome.

Use endsWith directly.

name.endsWith('001')

复制代码

image-20220124221035300

If we want to determine whether it ends with 'pinxia', as startsWith can skip a specified number of characters. endsWith can specify the first N characters as the object to check.

name.endsWith('半夏',8)

复制代码

We can specify the first 8 characters as the object to be checked, and the following characters will be ignored!

image-20220124221633486

.include()

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

const name = '123456半夏001';
复制代码

image-20220124221838309

.repeat()

repeat will repeat the current string a specified number of times.

For example, we repeat 123 10 times.

'123'.repeat(10)
复制代码

image-20220124222313480

The usage scenarios of this repeat may be slightly less, but it can also be used in some strange needs.

For example: if we want to output three strings of inconsistent lengths in the terminal and require right alignment, what do we need to do!

image-20220124222829695

First of all, we need to confirm that the repeated string is a space, but the number of repetitions is inconsistent. What should we do?

leftPad = function(str, length ){
    return `${' '.repeat(Math.max(length - str.length,0))}${str}`;
}
复制代码

Guess you like

Origin juejin.im/post/7083859293585276935