BabelJs - 編譯 ES8 功能為 ES5



字串填充是新增到 javascript 中的新的 ES8 功能。我們將使用一個簡單的示例,該示例將使用 babel 將字串填充編譯為 ES5。

字串填充

字串填充會根據指定的長度從左側新增另一個字串。字串填充的語法如下所示 −

語法

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

示例

const str = 'abc';

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

輸出

_____abc
abc_____

ES8 - 字串填充

const str = 'abc';

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

命令

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, '_'));

js 必須與 babel-polyfill 一起使用,如下所示 −

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
廣告