Javascript 如何替换特定位置的字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2236235/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to replace a string at a particular position
提问by Harish
Is there a way to replace a portion of a String at a given position in java script. For instance I want to replace 00in the hours column with 12in the below string.The substringcomes at 13 to 15.
有没有办法在java脚本中的给定位置替换字符串的一部分。例如,我想00在小时列中替换12为下面的字符串substring。在 13 到 15 之间。
Mar 16, 2010 00:00 AM
回答by Daniel Vassallo
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.
请注意,如果您打算使用它来操作日期,则建议改用一些日期操作方法,例如DateJS 中的方法。
回答by YOU
A regex approach
正则表达式方法
"Mar 16, 2010 00:00 AM".replace(/(.{13}).{2}/,"2")
Mar 16, 2010 12:00 AM
回答by AutomatedTester
One option would be
一种选择是
>>> var test = "Mar 16, 2010 00:00 AM";
>>> test.replace(test.substring(13,15),"12")
回答by Haim Evgi
if it is always 00:in hours,
如果总是 00:以小时为单位,
you can just replace 00:with 12:
你可以 00:用12:
using replace(),
使用replace(),
if not u need find the indexOfthe :character ,
如果不是你需要找到indexOf这个:角色,
and then replace 2 digit before with 12.
然后用 替换之前的 2 位数字12。
回答by Suraj Chandran
回答by Slavik Meltser
Another creative idea could be converting into Array, spliceand convert it back to String.
另一个创意可能是转换成数组,splice然后再转换回字符串。
let str = "Mar 16, 2010 00:00 AM";
let arr = str.split("");
arr.splice(13,2,"1","2");
str = arr.join("");

