javascript - Format and replace a string with a regular expression -


i have number that's @ least 7 digits long. typical examples: 0000123, 00001234, 000012345

i want transform them become respectively: 01:23, 12:34, 23:45

which mean replacing whole string last 4 characters , putting colon in middle.

i can last 4 digits (\d{4})$ , can 2 groups this: (\d{2})(\d{2})$

with last option, on string 0000123 $1:$2 match gives me 00001:23 want 01:23

i replace string so:

newval = val.replace(/regex/, '$1:$2'); 

you need match beginning digits \d* (or .* if there can anything):

var val = "0001235";  var newval = val.replace(/^\d*(\d{2})(\d{2})$/, '$1:$2');  console.log(newval);

pattern details:

  • ^ - start of string
  • \d* - 0+ digits (or .* match 0+ chars other line break chars)
  • (\d{2}) - group 1 capturing 2 digits
  • (\d{2}) - group 2 capturing 2 digits
  • $ - end of string.

Comments

Popular posts from this blog

php - Vagrant up error - Uncaught Reflection Exception: Class DOMDocument does not exist -

vue.js - Create hooks for automated testing -

Add new key value to json node in java -