Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Create preparse-postformat.md #58

Merged
merged 2 commits into from
Nov 8, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
66 changes: 66 additions & 0 deletions docs/plugin/preparse-postformat.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
---
id: preparse-postformat
title: Pre-parse / Post-format Plugin
---
Pre-parse / Post-format lets you process the input before the parser and process the string output after the formatter. [Based on similar behavior for locales in moment.js](https://momentjs.com/docs/#/i18n/locale-data/).

NOTE: this plugin requires the localeData plugin to be imported before it (as it depends on it's functionality). This is done [by design](https://github.com/iamkun/dayjs/pull/1255#issuecomment-753325420).

NOTE: this plugin also affects the relative time plugin, also by design (mimics the moment.js implementaiton behavior).

## Sample usage
e.g. [In the AR locale specifically, it is used to support Arabic numerals](https://github.com/iamkun/dayjs/pull/1255/commits/e26e802d767eec89aae02c8cecf87f517600a698).

```javascript
// Arabic [ar]
import dayjs from 'dayjs'

const months = 'يناير_فبراير_مارس_أبريل_مايو_يونيو_يوليو_أغسطس_سبتمبر_أكتوبر_نوفمبر_ديسمبر'.split('_')
const symbolMap = {
1: '١',
2: '٢',
3: '٣',
4: '٤',
5: '٥',
6: '٦',
7: '٧',
8: '٨',
9: '٩',
0: '٠'
}

const numberMap = {
'١': '1',
'٢': '2',
'٣': '3',
'٤': '4',
'٥': '5',
'٦': '6',
'٧': '7',
'٨': '8',
'٩': '9',
'٠': '0'
}

const locale = {
name: 'ar',
// ...
preparse(string) {
return string
.replace(
/[١٢٣٤٥٦٧٨٩٠]/g,
match => numberMap[match]
)
.replace(/،/g, ',')
},
postformat(string) {
return string
.replace(/\d/g, match => symbolMap[match])
.replace(/,/g, '،')
},
// ...
}
// ...
```

[The tests](https://github.com/VehpuS/dayjs/blob/e565267d925b40af8c7e0663c303f9a397372d03/test/plugin/preParsePostFormat.test.js) should also give you a good idea on how to use the plugin if this isn't clear enough ;).
1 change: 1 addition & 0 deletions website/sidebars.json
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,7 @@
"plugin/min-max",
"plugin/object-support",
"plugin/plural-get-set",
"plugin/preparse-postformat",
"plugin/quarter-of-year",
"plugin/relative-time",
"plugin/timezone",
Expand Down