Lesson 6. New string methods

 

After reading lesson 6, you will

  • Know how to use String.prototype.startsWith
  • Know how to use String.prototype.endsWith
  • Know how to use String.prototype.includes
  • Know how to use String.prototype.repeat
  • Know how to use String.prototype.padStart
  • Know how to use String.prototype.padEnd

None of these methods would be extremely difficult to implement, but they are tasks that are used enough to warrant inclusion in the standard library.

Consider this

Let’s say you’re writing a function that tells the current time. Using an instance of the Date object, you can get the current hour and minutes with the getHours and getMinutes methods, respectively:

function getTime() {
  const date = new Date();
  return date.getHours() + ':' + date.getMinutes();
}

But if the current time were 5:06 a.m., this function would return the string 5:6. How can you fix the function so that the minutes side is always two digits?

6.1. Searching strings

Imagine you’re loading products from a database. The product data comes from several different manufacturers and isn’t normalized. Because of this, some of the prices are in the format 499.99 without a leading $, whereas others are in the format $37.95 with a leading $. When you display the price on the web page, you can’t simply prefix all prices with a $ because that would make some have a double dollar sign like this: $$37.95.

You could easily tell if the first character is a $ like so:

if( price[0] === '$' ) {
  // price starts with $
}

6.2. Padding strings

Summary