0

I'm looking for an easy and best practice solution to add the string : after 2 characters in my string.

My string looks like this: 1100. Now I would like to have the result: 11:00.

I've found only many solutions to add : after 2 characters, but they also will add : after 00 because the solution is to add : after every 2 characters.

That's not what I want, I need only one addition of : after 2 characters.

Can you help me?

nielsv
  • 6,540
  • 35
  • 111
  • 215

3 Answers3

1
var str = "1100";

var result= str.substring(0,2) + ":" + str.substring(2);

console.log(result)

DEMO

Akki619
  • 2,386
  • 6
  • 26
  • 56
0

Try this:

var txt1 = "1100"
var txt2 = txt1.slice(0, 2) + ":" + txt1.slice(2);
vijayP
  • 11,432
  • 5
  • 25
  • 40
0

var string = "foo baz";
var index = 4
var result = string.slice(0, index) + "bar" + string.slice(index);

alert(result); 
rrk
  • 15,677
  • 4
  • 29
  • 45