Repeat Character N Times

2019-01-01 06:25发布

In Perl I can repeat a character multiple times using the syntax:

$a = "a" x 10; // results in "aaaaaaaaaa"

Is there a simple way to accomplish this in Javascript? I can obviously use a function, but I was wondering if there was any built in approach, or some other clever technique.

21条回答
看风景的人
2楼-- · 2019-01-01 06:54
String.prototype.repeat = function (n) { n = Math.abs(n) || 1; return Array(n + 1).join(this || ''); };

// console.log("0".repeat(3) , "0".repeat(-3))
// return: "000" "000"
查看更多
梦该遗忘
3楼-- · 2019-01-01 06:56

Here is an ES6 version

const repeat = (a,n) => Array(n).join(a+"|$|").split("|$|");
repeat("A",20).forEach((a,b) => console.log(a,b+1))

查看更多
路过你的时光
4楼-- · 2019-01-01 06:58

In CoffeeScript:

( 'a' for dot in [0..10]).join('')
查看更多
登录 后发表回答