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()
?
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()
?
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