violet0sea / note

can not open gist, so write here
0 stars 0 forks source link

string replace在特定位置插入字符 #5

Open violet0sea opened 7 years ago

violet0sea commented 7 years ago

有这样一个日期"20170821",想转化为"2017-08-21" 使用正则加replace完成相应操作 了解一下replace用法 string.replace(regexp|replacedString, newString|function[, flags]) 另外需要使用$做匹配占位符 var date = "20170821"; var pattern = /(\w{4})(\w{2})/; var str = date.replace(pattern, '$1-$2-'); // "2017-08-21" $1、$2代表 第1、2个括号匹配的字符串