Formatting Strings with JavaScript padStart() and padEnd()

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

内容简介: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


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

查看所有标签

猜你喜欢:

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

创投42章经

创投42章经

曲凯 / 中信出版集团 / 2018-10-20 / 58.00

《创投42章经》是拥有百万粉丝的微信公众号“42章经”的精选文章合集,全书共分为心法、内功、招式和江湖传奇四部分。 在心法部分,读者可以学到一些创业与投资的底层思维方式;在内功部分,读者可以了解到,投资人看待一家公司经营状况的标准;在招式部分,读者可以看到作者作为一名资深投资人和睿智的观察者,对过去几年主要的公司、模式以及风口的判断;最后的江湖传奇部分,作者通过一些故事,帮助读者更好地理解当......一起来看看 《创投42章经》 这本书的介绍吧!

CSS 压缩/解压工具
CSS 压缩/解压工具

在线压缩/解压 CSS 代码

随机密码生成器
随机密码生成器

多种字符组合密码

UNIX 时间戳转换
UNIX 时间戳转换

UNIX 时间戳转换