javascript - Find a space before some numbers(time format) in regular expression -
i have string , want regular expression find whether there space before number or not, if yes, add 1 space before that. example: "taxi cabs thurs-fri-sat 11:30pm-3:00am" , result: "taxi cabs thurs-fri-sat 11:30 pm-3:00 am"
i'm not regular expression expert, ended these 2 variants:
- first variant using callback function second parameter
replacemethod:
var str = 'taxi cabs thurs-fri-sat 11:30pm-3:00am'; var strupdated = str.replace(/\d?\d:\d?\d(am|pm)/g, function(m){ return m.replace(/(am|pm)/g, " $1"); }); console.log('old: ' + str); console.log('new: ' + strupdated); - second variant using expression second parameter
replacemethod:
var str = 'taxi cabs thurs-fri-sat 11:30pm-3:00am'; var strupdated = str.replace(/(\d?\d:\d?\d)(am|pm)/g, "$1 $2"); console.log('old: ' + str); console.log('new: ' + strupdated); console.log('----------------------------------'); var str = 'another test 1:22 am. 12:05pm , 12:50pn '; var strupdated = str.replace(/(\d?\d:\d?\d)(am|pm)/g, "$1 $2"); console.log('old: ' + str); console.log('new: ' + strupdated); now try explain regex :)
(\d?\d:\d?\d)- match digits 1:1, 11:22, 1:22, 11:2, brakes used make group later use in replace regex (second parameter of replace method)(am|pm)- group ( create when put brackets ) match literal or pm
edit (in response comment)
what can propose take care cases 11am-6pm or 8a-6p in regex , not complicate current one. have on following code - second replace doing job:
var str = 'taxi cabs thurs-fri-sat 11:30pm-3:00am \r\n 11am-6pm or 8a-6p 11m-6m or 12a-15p'; var strupdated = str.replace(/(\d?\d:\d?\d)(am|pm)/g, "$1 $2").replace(/(\d?\d)(am|pm|a|p)/g, "$1 $2"); console.log('old: ' + str); console.log('new: ' + strupdated);
Comments
Post a Comment