20

Is there a way to replace a portion of a String at a given position in java script. For instance I want to replace 00 in the hours column with 12 in the below string.The substring comes at 13 to 15.

Mar 16, 2010 00:00 AM 
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
Harish
  • 3,343
  • 15
  • 54
  • 75

6 Answers6

39

The following is one option:

var myString = "Mar 16, 2010 00:00 AM";

myString = myString.substring(0, 13) + 
           "12" + 
           myString.substring(15, myString.length);

Note that if you are going to use this to manipulate dates, it would be recommended to use some date manipulation methods instead, such as those in DateJS.

Daniel Vassallo
  • 337,827
  • 72
  • 505
  • 443
  • 6
    A slightly faster and more concise approach: for the second part of the string, use `myString.substr(15)` - this will get the string from position `15` till the end of the string. –  Mar 23 '18 at 07:00
8

A regex approach

"Mar 16, 2010 00:00 AM".replace(/(.{13}).{2}/,"$112")
Mar 16, 2010 12:00 AM
YOU
  • 120,166
  • 34
  • 186
  • 219
  • 2
    I like this approach but if anyone is concerned about the performance here's a test comparison: http://jsperf.com/substring-replace – user1510539 Mar 16 '16 at 15:07
  • 1
    right, regex are generally slower. That I won't use myself in 2016. – YOU Mar 17 '16 at 05:51
  • 1
    Ten times slower, but still extremely fast unless you need to perform a million operations per second. –  Mar 23 '18 at 06:59
3

One option would be

>>> var test = "Mar 16, 2010 00:00 AM";
>>> test.replace(test.substring(13,15),"12")
AutomatedTester
  • 22,188
  • 7
  • 49
  • 62
  • 1
    Wouldn't that give "Mar 16, 2010 12:12 AM"? You could change it to `test.replace(test.substring(13,16),"12:")` I think (similar to haim's method). – Dominic Rodger Feb 10 '10 at 11:10
  • 3
    @Dominic: Good point, but actually it will replace it correctly in this case, because the JavaScript replace() method only replaces the first occurrence. But if the date was "Mar 16 2000", it would not have worked. – Daniel Vassallo Feb 10 '10 at 11:13
  • @Daniel - interesting - seems like an odd implementation of String::replace. Thanks for the correction! – Dominic Rodger Feb 10 '10 at 11:22
3

if it is always 00: in hours,

you can just replace 00: with 12:

using replace() ,

if not u need find the indexOf the : character ,

and then replace 2 digit before with 12.

Haim Evgi
  • 123,187
  • 45
  • 217
  • 223
0

You can direclty use replace() method along with indexOf() of string in Javascript.

Suraj Chandran
  • 24,433
  • 12
  • 63
  • 94
0

Another creative idea could be converting into Array, splice and convert it back to String.

let str = "Mar 16, 2010 00:00 AM";
let arr = str.split("");
arr.splice(13,2,"1","2");
str = arr.join("");
Slavik Meltser
  • 9,712
  • 3
  • 47
  • 48