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,200
  • 31
  • 105
  • 208

3 Answers3

1
var str = "1100";

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

console.log(result)

DEMO

Akki619
  • 2,334
  • 5
  • 23
  • 51
0

Try this:

var txt1 = "1100"
var txt2 = txt1.slice(0, 2) + ":" + txt1.slice(2);
vijayP
  • 11,352
  • 5
  • 24
  • 38
0

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

alert(result); 
rrk
  • 15,214
  • 4
  • 26
  • 42