BabelJS - Transpile ES8 features to ES5



String padding is the new ES8 feature added to javascript. We will work on simple example, which will transpile string padding to ES5 using babel.

String Padding

String padding adds another string from the left side as per the length specified. The syntax for string padding is as shown below −

Syntax

str.padStart(length, string);
str.padEnd(length, string);

Example

const str = 'abc';

console.log(str.padStart(8, '_'));
console.log(str.padEnd(8, '_'));

Output

_____abc
abc_____

ES8 - String Padding

const str = 'abc';

console.log(str.padStart(8, '_'));
console.log(str.padEnd(8, '_'));

command

npx babel strpad.js --out-file strpad_es5.js

Babel - ES5

'use strict';

var str = 'abc';

console.log(str.padStart(8, '_'));
console.log(str.padEnd(8, '_'));

The js has to be used along with babel-polyfill as shown below −

test.html

<!DOCTYPE html>
<html>
   <head>
      <title>BabelJs Testing</title>
   </head>
   <body>
      <script src="node_modules\babel-polyfill\dist\polyfill.min.js" type="text/javascript"></script>
      <script type="text/javascript" src="strpad_es5.js"></script>
   </body>
</html>

String Padding
Advertisements