views:

131

answers:

5

Is there way of generating a string made up of 250 underscores, without using a loop? I want to avoid writing code like this:

var myString= '';
for (var i=0; i < 250; i++) {
    myString += '_';
}
A: 
var myString = "__________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________";

Why do you want to generate it? And why do you want to avoid a for loop?

Bombe
Because the string size can vary on different occasions. I was sure there was an easier approach, something like: var myString = new char('_', 250); or something similar?
Andy
Write a method that accepts the string size n and returns a string of n underscores. Because a for loop is the most straight forward and AFAIK, the fastest way to do this.
Amarghosh
+7  A: 

There's no built-in solution but the question Repeat String - Javascript has a nice solution:

If you don't want to alter the String prototype you can just do:

var num = 250;
var myChar = '_';
var myString = new Array(num + 1).join(myChar);

This is creating an array of 251 undefineds an then joining them by your character. Since undefined is '' (empty string) when converted to a string in .join(), this gives you the string you're after.

Greg
actually, `undefined` converted to string is `"undefined"` and not the empty string; that `undefined` and `null` entries of the arry will be converted to `""` is particular to `join()`
Christoph
right - edited to clarify
Greg
Wow, this is probably one of the most convoluted ways to create a string that only contains a single repeating character.
Bombe
@Bombe: using arrays as string builders isn't uncommon, so it's not really that far fetched...
Christoph
+1  A: 

Use a constant that is longer that the longest number of underscores and use substring() to get as many as you need.

Aaron Digulla
+2  A: 

Its a bit of a hack, but you could do something like:

var arr = new Array(251);
var lineStr = arr.toString().replace(/,/g, "_");
James
A: 

Here's a function which creates the string in (more or less) logarithmic runtime:

function repeat(string, times) {
    if(!(times = +times)) return ''; // convert to number; check for NaN, 0
    var result = '' + string, i = 1;
    for(; i * 2 <= times; i *= 2) result += result;
    for(; i < times; ++i) result += string;
    return result;
}

var u250 = repeat('_', 250);

Hopefully, I didn't mess up the loop conditions ;)

Also, Aaron's suggestion can be automated:

function underscores(count) {
    while(count > underscores.buffer.length)
        underscores.buffer += underscores.buffer;
    return underscores.buffer.substring(0, count);
}
underscores.buffer = '_';

var u250 = underscores(250);
Christoph