天天看點

JavaScript string repeat methods All In One

JavaScript string repeat methods All In One

JavaScript string repeat methods All In One

repeat

padStart

padEnd

There are many ways in the ES-Next ways

ES2015 / ES6
/** 
 * str: String
 * count: Number
 */
const str = `hello repeat!\n`, count = 3;

let resultString = str.repeat(count);

console.log(`resultString = \n${resultString}`);
/*
resultString = 
hello repeat!
hello repeat!
hello repeat!
*/

({ toString: () => 'abc', repeat: String.prototype.repeat }).repeat(2);
// 'abcabc' (repeat() is a generic method)

// Examples

'abc'.repeat(0);    // ''
'abc'.repeat(1);    // 'abc'
'abc'.repeat(2);    // 'abcabc'
'abc'.repeat(3.5);  // 'abcabcabc' (count will be converted to integer)
// 'abc'.repeat(1/0);  // RangeError
// 'abc'.repeat(-1);   // RangeError

      

ES2017 / ES8
const str = 'abc ';
const times = 3;

const newStr = str.padStart(str.length * times, str.toUpperCase());

console.log(`newStr =`, newStr);
// "newStr =" "ABC ABC abc "

      

const str = 'abc ';
const times = 3;

const newStr = str.padEnd(str.length * times, str.toUpperCase());

console.log(`newStr =`, newStr);
// "newStr =" "abc ABC ABC "

      

refs

​​https://stackoverflow.com/a/41574167/5934465​​

​​https://www.ecma-international.org/ecma-262/6.0/#sec-string.prototype.repeat​​

​​https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/repeat​​

​​https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padStart​​

​​https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padEnd​​

​​https://www.freecodecamp.org/news/three-ways-to-repeat-a-string-in-javascript-2a9053b93a2d/​​

JavaScript string repeat methods All In One

​​

JavaScript string repeat methods All In One

©xgqfrms 2012-2020

釋出文章使用:隻允許注冊使用者才可以通路!

xgqfrms