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!

3
  • this plugin might help docs.jquery.com/Plugins/Validation/… Commented Jul 23, 2013 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 Commented Jul 23, 2013 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. Commented Jul 23, 2013 at 19:32

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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: printf, originally, yes. But the sprintf library actually returns a string.
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...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.