Home > Web Front-end > JS Tutorial > body text

Detailed explanation of padStart() and padEnd() methods in JavaScript

青灯夜游
Release: 2020-12-09 18:01:36
Original
4983 people have browsed it

Detailed explanation of padStart() and padEnd() methods in JavaScript

ES2017 introduces the function of string completion length. If a string is not long enough, it will be completed at the head or tail. padStart() is used for head completion , padEnd() is used for tail completion.

const string = 'hi';

string.padStart(3, 'c'); // "chi"

string.padEnd(4, 'l'); // "hill"
Copy after login

Syntax

string.padStart(<maxLength>, <padString>)

string.padEnd(<maxLength>, <padString>)
Copy after login

Understanding the parameters

padEnd and padStart accept the same parameters.

1. maxLength

The length of the final string.

const result = string.padStart(5);

result.length; // 5
Copy after login

When I saw this, it also took me a while to learn. I always thought maxLength was the number of times the string parameter was repeatedly filled. So I just want to emphasize that this parameter is the target length that the current string needs to be filled to, not the number of times the filling string is repeated . If this value is less than the length of the current string, the current string itself is returned.

Of course, I believe readers are much smarter than me, so I’m sure you don’t have this confusion??

2. padString

padString means padding string. If the string is too long and the padded string length exceeds the target length, only the leftmost part is retained and the other parts are truncated. The default value of this parameter is a space " "(U 0020.

&#39;hi&#39;.padStart(5);

// 等价于
&#39;hi&#39;.padStart(5, &#39; &#39;);
Copy after login

If you pass in an empty string, nothing will be filled in.

const result = &#39;hi&#39;.padStart(5, &#39;&#39;);

result; // "hi"
result.length; // 2
Copy after login

How to handle other data types

For the second parameter padString, it accepts a string. If we try to pass in other data types to it. It will Call the toString method to force conversion to a string. Let's see what happens when using toString on different value types.

// Number
(100).toString(); // &#39;100&#39;

// Boolean
true.toString();   // &#39;true&#39;
false.toString();  // &#39;false&#39;

// Array
[&#39;A&#39;].toString(); // &#39;A&#39;
[&#39;&#39;].toString();  // &#39;&#39;

// Object
({}).toString();         // &#39;[object Object]&#39;
({hi: &#39;hi&#39;}).toString(); // &#39;[object Object]&#39;
Copy after login

With this knowledge, Let's see if we can pass these other value types to padStart (padEnd has the same behavior).

&#39;SAM&#39;.padStart(8, 100);    // &#39;10010SAM&#39;

&#39;SAM&#39;.padStart(8, true);   // &#39;truetSAM&#39;
&#39;SAM&#39;.padStart(8, false);  // &#39;falseSAM&#39;

&#39;SAM&#39;.padStart(5, [&#39;&#39;]);   // &#39;SAM&#39;
&#39;SAM&#39;.padStart(5, [&#39;hi&#39;]); // &#39;hiSAM&#39;

&#39;SAM&#39;.padStart(18, {});         // &#39;[object Object]SAM&#39;
&#39;SAM&#39;.padStart(18, {hi: &#39;hi&#39;}); // &#39;[object Object]SAM&#39;
Copy after login

Handlingundefined

Here is an interesting example. If you force undefined to be converted into a string, you will get a TypeError:

undefined.toString(); // TypeError: Cannot read property &#39;toString&#39; of undefined
Copy after login

But when we pass undefined as the second parameter to padStart, we will get this:

&#39;SAM&#39;.padStart(10, undefined);
// &#39;       SAM&#39;
Copy after login

So the ## mentioned above #padString The parameters will be forced to be converted into strings using toString. It feels wrong again here??. Let’s take a look at the specification first:

ECMAScript specification: If the padded string is undefined, the padded string will be regulated as a space (0x0020).
Okay, let’s correct it, except

undefined , otherwise all other data types passed will be coerced to strings using toString.

What if padString exceeds maxLength?

What if

maxLength If the value is less than or equal to the length of the current string, then the current string itself is returned.

&#39;hi&#39;.padEnd(2, &#39;SAM&#39;);
// &#39;hi&#39;
Copy after login

If

maxLength is less than the length of padString, then padString will be truncated.

&#39;hi&#39;.padEnd(7, &#39;SAMANTHA&#39;);
// &#39;hiSAMAN&#39;
Copy after login

padStart/padEnd vs padLeft/padRight

trim Alias ​​the method has.

  • trimLeft is an alias for trimStart
  • trimRight is an alias for trimStart
but for String padding method, no aliases. So don't use

padLeft and padRight, they don't exist. This is also the reason why it is recommended that you do not use trimaliases, so as to ensure consistency in the code base??

Practical use

Use padStart to right-align the string

console.log(&#39;JavaScript&#39;.padStart(15));
console.log(&#39;HTML&#39;.padStart(15));
console.log(&#39;CSS&#39;.padStart(15));
console.log(&#39;Vue&#39;.padStart(15));
Copy after login

Results obtained

     JavaScript
           HTML
            CSS
            Vue
Copy after login

Digital coding

const bankNumber = &#39;2222 2222 2222 2222&#39;;
const last4Digits = bankNumber.slice(-4);

last4Digits.padStart(bankNumber.length, &#39;*&#39;);
// ***************2222
Copy after login
Browser support

padStart and padEnd are Introduced at the same time, so they share similar browser support, except IE, they can be used??

Original address: https://dmitripavlutin.com/replace-all-string-occurrences -javascript/

Author: Dmitri Pavlutin

Translation address: https://segmentfault.com/a/1190000023721944

For more programming-related knowledge, please visit :

Introduction to Programming! !

The above is the detailed content of Detailed explanation of padStart() and padEnd() methods in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:segmentfault.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!