Asked  7 Months ago    Answers:  5   Viewed   14 times

What is the best or most concise method for returning a string repeated an arbitrary amount of times?

The following is my best shot so far:

function repeat(s, n){
    var a = [];
    while(a.length < n){
        a.push(s);
    }
    return a.join('');
}

 Answers

88

Good news! String.prototype.repeat is now a part of JavaScript.

"yo".repeat(2);
// returns: "yoyo"

The method is supported by all major browsers, except Internet Explorer. For an up to date list, see MDN: String.prototype.repeat > Browser compatibility.

MDN has a polyfill for browsers without support.

Tuesday, June 1, 2021
 
shin
answered 7 Months ago
68

These days, the repeat string method is implemented almost everywhere. (It is not in Internet Explorer.) So unless you need to support older browsers, you can simply write:

"a".repeat(10)

Before repeat, we used this hack:

Array(11).join("a") // create string with 10 a's: "aaaaaaaaaa"

(Note that an array of length 11 gets you only 10 "a"s, since Array.join puts the argument between the array elements.)

Simon also points out that according to this jsperf, it appears that it's faster in Safari and Chrome (but not Firefox) to repeat a character multiple times by simply appending using a for loop (although a bit less concise).

Tuesday, June 1, 2021
 
FyodorX
answered 7 Months ago
24

No, string primitives do not have methods. As with numeric primitives, the JavaScript runtime will promote them to full-blown "String" objects when called upon to do so by constructs like:

var space = "hello there".indexOf(" ");

In some languages (well, Java in particular, but I think the term is in common use) it's said that the language "boxes" the primitives in their object wrappers when appropriate. With numbers it's a little more complicated due to the vagaries of the token grammar; you can't just say

var foo = 27.toLocaleString();

because the "." won't be interpreted the way you'd need it to be; however:

var foo = (27).toLocaleString();

works fine. With string primitives — and booleans, for that matter — the grammar isn't ambiguous, so for example:

var foo = true.toString();

will work.

Wednesday, June 2, 2021
 
Ultimater
answered 7 Months ago
79
def repeat_to_length(string_to_expand, length):
   return (string_to_expand * ((length/len(string_to_expand))+1))[:length]

For python3:

def repeat_to_length(string_to_expand, length):
    return (string_to_expand * (int(length/len(string_to_expand))+1))[:length]
Thursday, June 3, 2021
 
nighter
answered 7 Months ago
48

Your first example does not actually output a string to the console. Notice how properties is passed as a separate parameter argument (as it is surrounded by commas , and not string-concatenation operators +).

When you pass an object (or any JavaScript value) to console as a discrete argument it can display it how it wishes - including as an interactive formatted display, which it does in your first example.

In your second example, you're using templated-strings, but it's (generally) equivalent to this:

logString = "Description: " + description.toString() + ". Properties: " + properties.toString()";

And Object.prototype.toString() returns "[object Object]" by default. Note that this is a string value which is not particularly useful.

In order to get a JSON (literally JavaScript Object Notation) representation of an object used in a templated string use JSON.stringify:

logString = `Description: ${ description }. Properties: ${ JSON.stringify( properties ) }.`

Or consider extending toString for your own types:

myPropertiesConstructor.prototype.toString = function() {
    return JSON.stringify( this );
};
Thursday, July 29, 2021
 
DilbertDave
answered 5 Months ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :  
Share