String Padding and Trimming
Posted on September 10, 2020 in JavaScript by Matt Jennings
The code below was added to the JavaScript library in ES2017 (string padding) and ES2019 (string trimming).
.padStart();
// Code below works for LTR languages (like English) // and RTL languages (like Arabic) var str = "Hello"; str.padStart( 5 ); // "Hello" str.padStart( 8 ); // " Hello" str.padStart( 8, "*" ); // "***Hello" str.padStart( 8, "12345" ); // "123Hello" str.padStart( 8, "ab" ); // "abaHello" var str2 = "Hello";
.padEnd();
var str = "Hello"; str.padEnd( 5 ); // "Hello" str.padEnd( 8 ); // "Hello " str.padEnd( 8, "*" ); // "Hello***" str.padEnd( 8, "12345" ); // "Hello123" str.padEnd( 8, "ab" ); // "Helloaba"
String Trimming
var str = " some stuff \t\t"; str.trim(); // "some stuff" str.trimStart(); // "some stuff " str.trimEnd(); // " some stuff"