How to replace a string at a particular position

后端 未结 6 1471
深忆病人
深忆病人 2020-12-10 12:30

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 i

相关标签:
6条回答
  • 2020-12-10 12:56

    A regex approach

    "Mar 16, 2010 00:00 AM".replace(/(.{13}).{2}/,"$112")
    Mar 16, 2010 12:00 AM
    
    0 讨论(0)
  • 2020-12-10 12:58

    One option would be

    >>> var test = "Mar 16, 2010 00:00 AM";
    >>> test.replace(test.substring(13,15),"12")
    
    0 讨论(0)
  • 2020-12-10 13:01

    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.

    0 讨论(0)
  • 2020-12-10 13:04

    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.

    0 讨论(0)
  • 2020-12-10 13:04

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

    0 讨论(0)
  • 2020-12-10 13:04

    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("");
    
    0 讨论(0)
提交回复
热议问题