having fun with code

Little tricks: repeating strings in Javascript & Python

How many times have you found yourself printing strings like “————-” or “===========”? I do that a lot when I have to do console.logs or if I’m working on a console application or script. Adding dividers to the output makes it more readable.

Python has a very peculiar syntax for repeating strings, which consists in just multiplying the string by a number, like this:

  1. "123"*4 // returns "123123123123"

We can achieve the same in Javascript using Array.join() like this:

  1. Array(4).join("123"); // returns "123123123123"
  2. Array(30).join("-"); // returns "——————————"
  3. Array(2).join("<span>test</span>"); // returns "<span>test</span><span>test</span>"

Very useful for logs or to generate repeated html strings, etc.

Related Posts:

1 Tweet

1 Comment to Little tricks: repeating strings in Javascript & Python

  1. August 18, 2010 at 11:19 | Permalink

    New post: Little tricks: repeating strings in Javascript & Python http://bit.ly/ciRBWX

    This comment was originally posted on Twitter

Leave a Reply

You can use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Additional comments powered by BackType

About the blog

This is a blog about development, focused mainly on Javascript but also other languages like python, shell scripts and more.

About the author

Eneko Alonso is a software engineer and UI developer with more than eight years of experience in software and web development. He lives in San Luis Obispo, California and works at LEVEL Studios.

Contact Info

Contact Info

PromoteJS

JavaScript JS Documentation