0

If I have the following string:

var str = "2018Jun12-2018Jul11";

Is there a regular expression that I could use to convert it to: "Jun 12, 2018 - Jul 11, 2018" with str.replace()?

Dacre Denny
  • 26,362
  • 5
  • 28
  • 48
Legion
  • 3,295
  • 7
  • 39
  • 78

1 Answers1

1

Though this involves a bit of string formatting logic via a "replacer" callback, one solution that is based on String#replace() would be:

const input = `2018Jun12-2018Jul11`;
const output = input.replace(
  /* Search for matches of this pattern, and extract groups */
  /(\d+)([a-z]+)(\d+)/gi, 
  /* Replacer function formats the extracted values as required */
  (_,year,month,date) => `${month} ${date}, ${year}`
)
/* If you need white space around the hyphen */
.split('-').join(' - ')

console.log(input, ' -> ', output)

The idea here is to match any occurance of pattern "year number (\d+),month string [a-z]+, date number (\d+)" in your input string. The use of ( ) in the pattern causes corresponding values to be extracted from the pattern match. The replacer callback returns a string that rearranges those extracted values to the desired format. This string becomes the replacement value for the match in the output.

Hope that helps

Dacre Denny
  • 26,362
  • 5
  • 28
  • 48
  • It's really close, but for some reason the output string attaches the first digit of the date to the month name and the second digit is on it's own. The output I get is: `2018Jun12-2018Jul11 -> Jun1 2, 2018-Jul1 1, 2018` – Legion Feb 06 '20 at 00:16
  • @Legion that's because `\w` matches `0-9` as well so the `\w+` is absorbing the first digit in the day. You need `/(\d+)([a-z]+)(\d+)/gi` instead – Nick Feb 06 '20 at 00:29
  • That should be `[a-zA-Z]`, no? – Seb Feb 06 '20 at 00:30
  • @Seb `i` flag makes it case-insensitive – Nick Feb 06 '20 at 00:33
  • @Legion my appologies, I was tinkering with the regex and saved an error - just restored my prior answer :-) – Dacre Denny Feb 06 '20 at 00:48