Extended strings -padStart () and padEnd ()

ES6 is added to the new method String.prototype.padStart (maxLength, fillString = '') the length of the string or supplemented String.prototype.padEnd (maxLength, fillString = '') filled with a string.

maxLength to a predetermined length of the string. fillString = '' to add content.

padStart () in the completion string head.

padEnd () in the completion string tail.

 

. 1 'AA'.padStart (. 5,' B ')   // Output: BBBAA 
2 ' AA'.padStart (. 5, 'the BC')   // Output: BCBAA 
. 3  
. 4 'AA'.padEnd (. 5,' B ') // output: aabbb 
. 5 'AA'.padEnd (. 5,' the BC ') // output: AABCB

 

(1) If the original string is equal to or greater than a prescribed length to obtain the minimum length, returns the original string.

 

. 1 'AAAA'.padStart (2,' BB ') // Output: AAAA 
2 ' AAAA'.padEnd (2, 'BB') // Output: AAAA

 

(2) if the string is used both filled with the original string than the specified length and minimum length, it will exceed the number of bits of the completion string interception.

 

. 1 'AAA'.padStart (. 5,' the BCDE ') // Output: BCAAA 
2 ' AAA'.padEnd (. 5, 'the BCDE') // Output: AAABC

 

(3) If the second parameter is omitted, the default spaces completion. The following code is generated 10-bit string of numbers.

 

. 1 'A'.padStart (. 4) // Output:' A ' 
2 ' A'.padEnd (. 4) // Output: 'A'

Usage scenarios: Available on conversion issues in time format:

 

 1 var da = new Date()
 2 var y = da.getFullYear()
 3 var m = (da.getMonth()+1).toString().padStart(2,'0')
 4 var d = da.getDate().toString().padStart(2,'0')
 5 var h = da.getHours().toString().padStart(2,'0')
 6 var f = da.getMinutes().toString().padStart(2,'0')
 7 var s = da.getSeconds().toString().padStart(2,'0')
 8 
 9 return `${y}-${m}-${d} ${h}:${f}:${s}`
10 
11 //Because the time 2019-2-108 occur when the number of units: 10: Style 5 
12  @ may be used to complement code mode, output: 2019-02-10 08:10:05

 

 

  

 

Guess you like

Origin www.cnblogs.com/ghc520/p/11293814.html