正则表达式在javascript中删除左零的字符串

Regular expression in javascript to delete left zero in a string?

本文关键字:字符串 删除 javascript 正则表达式      更新时间:2023-09-26

如何用javascript创建正则表达式来删除字符串中的左零?


我有这个:

"2015年1月1日"


我需要获得这个:

"2015年1月1日"

如果这是一个日期,那么Zan的方法可能是更好的方法。但如果你真的想用正则表达式来实现,那么这里有一种方法:

只删除第一个前导零:

"01/01/2015".replace(/^0(.*)/,"$1")

更详细:

str = "01/01/2015"
pat = /^0(.*)/      // Match string beginning with ^, then a 0, then any characters.   
str.replace(pat,"$1")    // Replace with just the characters after the zero

删除每个分组中的前导零:

str = "01/01/2015"
pat = /(^|[/])0('d*)/g  //  Match string begin ^ or /, then a 0, then digits. 'g' means globally. 
str.replace(pat,"$1$2")  // Replace with the part before and after the 0.

您可以尝试不使用REGEX:

var myDate="01/01/2015";
var d = new Date(myDate);
alert(d.getDate() + '/' + (d.getMonth()+1) + '/' + d.getFullYear());

希望这就是您想要的:

s = '01/01/2015'; // check  11/01/2015 、11/11/2015、01/10/2015 ...
s = s.replace(/0*('d+)'/0*('d+)'/('d+)/,"$1/$2/$3");
alert(s);