我有字符串
Started: 11.11.2014 11:19:28.376<br/>Ended: 1.1.4<br/>1:9:8.378<br/>Request took: 0:0:0.2
我需要添加零以防万一我遇到1:1:8它应该是01:01:08同样适用于日期。我尝试使用
/((:|\.|\s)[0-9](:|\.))/g
但它没有给出所有可能的重叠匹配。如何解决?
var str = "Started: 11.11.2014 11:19:28.376<br/>Ended: 11.11.2014<br/>11:19:28.378<br/>Request took: 0:0:0.2";
var re = /((:|\.|\s)[0-9](:|\.))/g
while ((match = re.exec(str)) != null) {
//alert("match found at " + match.index);
str = [str.slice(0,match.index), '0', str.slice(match.index+1,str.length)];
}
alert(str);
答案 0 :(得分:0)
这可能会做你想要的:
str.replace(/\b\d\b/g, "0$&")
它搜索单个数字\d
,并在前面填充0
。
第一个单词边界\b
检查前面没有[a-zA-Z0-9_]
,第二个单词检查数字后面没有[a-zA-Z0-9_]
。
$&
指的是整个匹配。
如果您想填充0
,只要前后字符不是数字:
str.replace(/(^|\D)(\d)(?!\d)/g, "$10$2")