Strings in ES2015+

Today we will take a look at some new string-related features, which you can start using in modern browsers right now. These are template literals, .includes(), padding and repeat.

Template literals MDN

Template literals are one of my favourite recent Javascript features. If you find yourself constructing strings from variables frequently, you may be familiar with how unwieldy such a construction can become. The new template literals introduce the use of ` (backticks) instead of ' and ". To use variables inside template literals, you simply include it like ${variable}. It is worth knowing that inside ${...}, you can put any Javascript code you want, not just variables!

const protocol = 'https';
const website = '';
const userId = 1234;

// Old way
const oldUrl = protocol + '://' + website + '?' + userId;

// New way - template literals
const newUrl = `${protocol}://${website}?${userId}`;

// Not just variables ...
console.log(`2 + 2 is ${2 + 2}`); // '2 + 2 is 4'

Multiline strings

Template literals also allow the user of multiline strings. This is a new feature compared to normal quotation marks, where multiline is not possible without using the concatentation operator (+).

// Old way
const oldMultiStr = 'this is a ' +
                    'multiline string';

// New way
const newMultiStr = `this is a
                     multiline string`;

You should be careful with this, as all the whitespace within the backticks will be part of your string. Since the use of multiline strings is typically just to make the code more readable, this addition of extra whitespace could have unintended consequences.

string.includes() MDN

The new .includes() function for strings is a convenient way of checking if a string exists within another string. This has always been possible using indexOf, but this new funcion simply makes it easier to read.

const testString = 'Welcome to';

// Old way
testString.indexOf('') > -1; // true

// New way
testString.includes(''); // true

In addition to this, there are also similar functions which can be used with indexOf was used previously. These are startsWith and endsWith, and work as you’d expect.

String padding MDN

Back in March 2016, many web apps broke due to the sudden unpublishing of the npm leftpad package. This very simple package padded the left of a string with spaces or a specified character. Presumably as a result of this incident, the very useful feature of string padding is now part of Javascript. And twice as useful as leftpad, because you can pad on the right too!

// Left pad
const userId = '1234';
const paddedUserId = userId.padStart(8, '0');
console.log(paddedUserId); // '00001234';

// Right pad
const website = '';
const paddedWebsite = website.padEnd(16);
console.log(paddedWebsite); // '    ';

string.repeat() MDN

Have you ever wanted to repeat a string a certain number of times? It’s the kind of task usually confined to interviews, but if you need it, you can now do it easily in Javascript!

const strToRepeat = 'Test';
const timesToRepeat = 5;

// Old way
let oldRepeatStr = '';
for(let i=0; i<timesToRepeat; i++) {
  oldRepeatStr += strToRepeat;
console.log(oldRepeatStr); // 'TestTestTestTestTest'

// New way
const newRepeatStr = strToRepeat.repeat(5);
console.log(newRepeatStr); // 'TestTestTestTestTest'

Future string improvements

There are several improvements to strings in the pipeline right now, including one-sided string trimming and replaceAll. When (or if) these start to get implemented by browsers, you will find out about it here!

Other recent posts: