Formatting Strings with JavaScript padStart() and padEnd()

栏目: IT技术 · 发布时间: 5年前

内容简介:A few days ago, I was working on building a countdown timer in JavaScript, and I needed to format my seconds and milliseconds. I wanted the seconds to always be a length of 2 digits and the milliseconds to always be a length of 3 digits. In other words I w

A few days ago, I was working on building a countdown timer in JavaScript, and I needed to format my seconds and milliseconds. I wanted the seconds to always be a length of 2 digits and the milliseconds to always be a length of 3 digits. In other words I wanted 1 second to display as 01 and 1 millisecond to display as 001 .

Table of Contents

I ended up writing my own function to "pad" these numbers, but I found out there are built in functions in JavaScript, padStart() and padEnd() to do just that. In this article, let's look at how to leverage these built-in functions in JavaScript!

Let's start by covering a few different use cases for padding.

Labels and Values

Let's say you have labels and values on the same line, something like Name: James and Phone Number: (555)-555-1234 . If you stack these lines of different lengths on top of each other, it looks a bit odd. So instead of this...

Name: James
Phone Number: (555)-555-1234

You might want this.

Name:           James
Phone Number:   (555)555-1234

or this...

Name: James
Phone Number: (555)555-1234

Money

In America, it's customary to display two digits for the cents when displaying price. So instead of this...

$10.1

You would want this.

Our New React Course! Make 20 React Apps
$10.01

Dates

For dates, you want 2 digits for both the day and the month. So instead of this...

2020-5-4

You would want this.

2020-05-04

Timer

Similar to dates above, for a ms timer, you would want 2 digits for the seconds and 3 digits for the ms. So instead of this...

You would want this.

Let's start with padStart() (get it?!?) and with the label and value example. Let's say we want our labels to be right aligned with each other so that the values start at the same place.

Name: James
Phone Number: (555)555-1234

Since Phone Number is the longer of the two labels we want to pad the start of the Name label with spaces. For future sake though, let's not pad it specifically to the length of Phone Number, let's pad it to something longer, say 20 characters. This way, if you ever use longer labels in the future this trick will still work.

Before we pad, here's our starter code for displaying this info.

const label1 = "Name";
const label2 = "Phone Number";
const name = "James"
const phoneNumber = "(555)-555-1234";

console.log(label1 + ": " + name);
console.log(label2 + ": " + phoneNumber);

//Name: James
//Phone Number: (555)-555-1234

Now, let's pad the first label. For calling padStart() you need to pass two parameters: one for the target length of the padded string, and the second for the character you want to pad with . In this case, we want the length to be 20, and the padded character to be a space. It will look like.

const label1 = "Name";
const label2 = "Phone Number";
const name = "James"
const phoneNumber = "(555)-555-1234";

console.log(label1.padStart(20, " ") + ": " + name);
console.log(label2 + ": " + phoneNumber);

//               Name: James
////Phone Number: (555)-555-1234

And now to pad the second line.

const label1 = "Name";
const label2 = "Phone Number";
const name = "James"
const phoneNumber = "(555)-555-1234";

console.log(label1.padStart(20, " ") + ": " + name);
console.log(label2.padStart(20, " ") + ": " + phoneNumber);

//               Name: James
////     Phone Number: (555)-555-1234

With the same label and value example, let's change the way we pad the labels. Let's align the labels to the left so that we are adding padding at the end.

Starter code.

const label1 = "Name";
const label2 = "Phone Number";
const name = "James"
const phoneNumber = "(555)-555-1234";

console.log(label1 + ": " + name);
console.log(label2 + ": " + phoneNumber);

//Name: James
//Phone Number: (555)-555-1234

Now, let's pad the first label. Similar to what we did before with two small differences. Now, we are using padEnd() instead of padStart() and we need to concatenate the colon with the label before padding. This way we make sure the colon ends up in the right place.

const label1 = "Name";
const label2 = "Phone Number";
const name = "James"
const phoneNumber = "(555)-555-1234";

console.log((label1 + ': ').padEnd(20, ' ') + name);
console.log(label2 + ": " + phoneNumber);

//Name:               James
//Phone Number: (555)-555-1234

And now with both lines padded.

const label1 = "Name";
const label2 = "Phone Number";
const name = "James"
const phoneNumber = "(555)-555-1234";

console.log((label1 + ': ').padEnd(20, ' ') + name);
console.log((label2 + ': ').padEnd(20, ' ') + phoneNumber);

//Name:               James
//Phone Number:       (555)-555-1234

What About Numbers (prices, dates, timers,etc)

We haven't specified this yet (although it may be obvious), but the padding functions are specifically associated with strings not numbers. So, to pad a number, we need to first convert it to a string.

Price

Let's look at the starter code for displaying a price.

const dollars = 10;
const cents = 1;
console.log("$" + dollars + "." + cents); //$10.1

To pad our cents, we need to first convert it to a string, then call the padStart() function specifying a length of 1 and a pad character of '0';

const dollars = 10;
const cents = 1;
console.log("$" + dollars + "." + cents.toString().padStart(2,0)); //$10.01

Dates

Here's the starter code for a displaying a date.

const month = 2;
const year = 2020;

console.log(year + "-" + month); //2020-2

Now, let's pad the month to make sure it's two digits.

const month = 2;
const year = 2020;

console.log(year + "-" + month.toString().padStart(2,"0")); // 2020-02

Timer

And finally our timer. We have two different numbers we want to format, the seconds and the milliseconds. Same principle applies though. Here's the starter code.

const seconds = 1;
const ms = 1;

console.log(seconds + ":" + ms); //1:1

And now to pad. I'm going to do the padding on separate lines so that it is easier to read.

const seconds = 1;
const formattedSeconds = seconds.toString().padStart(2,0);
const ms = 1;
const formattedMs = ms.toString().padStart(3,0);

console.log(formattedSeconds + ":" + formattedMs); //01:001

Although writing your own padding function wouldn't be difficult, why do it yourself when it's built in to JavaScript? There's lots of nifty functions that are already built in. It's probably worth doing a quick search before you build something yourself.

Question for you. What are other useful functions in JavaScript that not many people know about? Let me know in the comments below or on twitter, @jamesqquick .

Like this article? Follow @jamesqquick on Twitter


以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

机器消灭秘密

机器消灭秘密

安迪•格林伯格 (Andy Greenberg) / 王崧、王涛、唐禾 / 重庆出版社 / 2017-8-10 / 49.8

《机器消灭秘密》一书中,格林伯格深入研究并生动再现了那些拥有全能技术的网络安全魔术师,他们将任何企图染指个人隐私的所谓国家机密的保密性打得粉碎。这本精心组织的著作是对此题材感兴趣的读者的必读之书,即便现在你可能不感兴趣,将来也极有可能希望了解这些内容,因为任何人都会不可避免地置身其中。无论你是初涉电脑屏幕之后的虚拟战场的新生,还是经验丰富的维基解密观察家,本书都是不可多得的上乘之作,你总会在其中发......一起来看看 《机器消灭秘密》 这本书的介绍吧!

URL 编码/解码
URL 编码/解码

URL 编码/解码

Markdown 在线编辑器
Markdown 在线编辑器

Markdown 在线编辑器

正则表达式在线测试
正则表达式在线测试

正则表达式在线测试