0

How do you format strings in Javascript? I wrote python code and I'm trying to translate it to javascript but I'm not too sure how

Python code:

def conv(t):
    return '%02d:%02d:%02d.%03d' % (
        t / 1000 / 60 / 60,
        t / 1000 / 60 % 60,
        t / 1000 % 60 + 12,
        t % 1000)

Does javascript/jquery let you do something similar to this? And if so, how?

Thanks!

user2494251
  • 33
  • 2
  • 9
  • this plugin might help http://docs.jquery.com/Plugins/Validation/jQuery.validator.format#templateargumentargumentN – Joran Beasley Jul 23 '13 at 19:30
  • I am pretty sure there are libraries that would allow you to do it. Javascript just has string concatenation and other string operations like regex replacement, substring, etc – akonsu Jul 23 '13 at 19:31
  • You don't really format strings in javascript like that. You have to use a library or extension. Basically you must use regex. – Travis J Jul 23 '13 at 19:32

2 Answers2

1

What you're referring to is basically a printf / String.Format-like operation. Unfortunately, JavaScript currently does not have any built-in way of doing this (which is too bad, really).

There are, of course, many libraries that give this kind of functionality.

Here's one of them (sprintf) which follows the printf syntax, and here's another one which uses the format syntax.

Community
  • 1
  • 1
voithos
  • 68,482
  • 12
  • 101
  • 116
  • It looks like printf doesn't let you return the string but only print it? :/ But I'll take a look at number formatting! – user2494251 Jul 23 '13 at 19:37
  • @user2494251: `printf`, originally, yes. But the `sprintf` library actually returns a string. – voithos Jul 23 '13 at 19:43
1

the closest i could come up with to your python code:

   function conv(t){
    t= [ 
        t / 1000 / 60 / 60,
        t / 1000 / 60 % 60,
        t / 1000 % 60 , 
        t % 1000 ].map( Math.floor );

        t[2]=t[2]+"."+( t.pop() + "0000").slice(0,3);

     return t.join(":").replace(/\b(\d)\b/g,"0$1");
   }

//test it out:
new Date(12345678).toISOString().split("T")[1].slice(0,-1); // == 03:25:45.678 
conv(12345678); // == 03:25:45.678

pardon if it's not correct, i don't know python, but this seems like what you're trying to do...

dandavis
  • 16,370
  • 5
  • 40
  • 36