javascript - Split integer into parts using RegExp -


i have input field , user may type time in different format(800,08:00,08:00 etc).i need display ever user input time format(xx:xx am/pm).

example:

1.'800'=>'08:00'; 2.'1245'=>'12:45'; 3.'1000 am'=>'10:00 am'; 4.'10.00 am'=>'10:00 am'; 5.'9 am'=>'09:00 am'; 

so type in "800" , convert "8:00" or type in "2145" , convert "21:45".

i have tried str.split(/[:;,. \/]/); ,but applicable in case of example 4.

you can use regex parse string components:

var myregexp = /^(\d{1,2}?)\d?(\d{2})?\b\s*([ap]m)?$/; var match = myregexp.exec(subject); if (match != null) {     hours = match[1];     minutes = match[2];     ampm = match[3]; }  

explanation:

^         # start of string (         # capture group 1:  \d{1,2}? # 1 or 2 digits, preferably 1 )         # end of group 1 \d?       # match optional non-digit (         # capture group 2:  \d{2}    # 2 digits )?        # end of (optional) group 2 \b        # end of number \s*       # optional whitespace (         # capture group 3:  [ap]m    # or pm )?        # end of (optional) group 3 $         # end of string 

you can use results construct new, normalized string, in case means

  • adding 0 if hours part single-digit
  • adding 00 if minutes part undefined
  • deciding if am/pm part undefined.

a regex can't part of exercise since regex can match text present in original string, not add dynamically.


Comments

Popular posts from this blog

html5 - What is breaking my page when printing? -

html - Unable to style the color of bullets in a list -

c# - must be a non-abstract type with a public parameterless constructor in redis -