Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace a string at a particular position

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 
like image 610
Harish Avatar asked Feb 10 '10 11:02

Harish


People also ask

How do you replace a character in a specific position in a string Java?

String are immutable in Java. You can't change them. You need to create a new string with the character replaced.


2 Answers

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.

like image 97
Daniel Vassallo Avatar answered Sep 20 '22 17:09

Daniel Vassallo


A regex approach

"Mar 16, 2010 00:00 AM".replace(/(.{13}).{2}/,"$112")
Mar 16, 2010 12:00 AM
like image 36
YOU Avatar answered Sep 19 '22 17:09

YOU