the editable site (validation-lab)
This commit is contained in:
commit
3ac81d5a52
13454 files changed
+2227005
No files matched your search
+87
@@ -0,0 +1,87 @@
|
||||
export type Options = {
|
||||
/**
|
||||
Add your own custom replacements.
|
||||
|
||||
The replacements are run on the original string before any other transformations. Both the string and the keys are normalized to NFC first, so a key matches canonically equivalent text.
|
||||
|
||||
This only overrides a default replacement if you set an item with the same key.
|
||||
|
||||
@default []
|
||||
|
||||
@example
|
||||
```
|
||||
import transliterate from '@sindresorhus/transliterate';
|
||||
|
||||
transliterate('Я люблю единорогов', {
|
||||
customReplacements: [
|
||||
['единорогов', '🦄']
|
||||
]
|
||||
})
|
||||
//=> 'Ya lyublyu 🦄'
|
||||
```
|
||||
|
||||
@example
|
||||
```
|
||||
import transliterate from '@sindresorhus/transliterate';
|
||||
|
||||
transliterate('foo & bar', {
|
||||
customReplacements: new Map([
|
||||
['&', 'and']
|
||||
])
|
||||
})
|
||||
//=> 'foo and bar'
|
||||
```
|
||||
*/
|
||||
readonly customReplacements?: ReadonlyArray<[string, string]> | Map<string, string>;
|
||||
|
||||
/**
|
||||
[BCP-47](https://developer.mozilla.org/en-US/docs/Glossary/BCP_47_language_tag) language tag for language-specific transliteration.
|
||||
|
||||
When specified, uses language-specific replacement rules for characters that have different transliterations in different languages.
|
||||
|
||||
The `no` and `nn` language codes are aliases for `nb`.
|
||||
|
||||
@example
|
||||
```
|
||||
import transliterate from '@sindresorhus/transliterate';
|
||||
|
||||
// Swedish: ä→a, ö→o, å→a
|
||||
transliterate('Räksmörgås', {locale: 'sv'});
|
||||
//=> 'Raksmorgas'
|
||||
|
||||
// German: ä→ae, ö→oe
|
||||
transliterate('Räksmörgås', {locale: 'de'});
|
||||
//=> 'Raeksmoergas'
|
||||
```
|
||||
*/
|
||||
readonly locale?: string;
|
||||
};
|
||||
|
||||
/**
|
||||
Convert Unicode characters to Latin characters using [transliteration](https://en.wikipedia.org/wiki/Transliteration).
|
||||
|
||||
Throws a `RangeError` if any string being normalized contains more than 100 consecutive Unicode combining marks. This includes the input, custom replacement keys, and intermediate results. The total string length is not limited.
|
||||
|
||||
@param string - String to transliterate.
|
||||
|
||||
@example
|
||||
```
|
||||
import transliterate from '@sindresorhus/transliterate';
|
||||
|
||||
transliterate('Fußgängerübergänge');
|
||||
//=> 'Fussgaengeruebergaenge'
|
||||
|
||||
transliterate('Я люблю единорогов');
|
||||
//=> 'Ya lyublyu edinorogov'
|
||||
|
||||
transliterate('أنا أحب حيدات');
|
||||
//=> 'ana ahb hydat'
|
||||
|
||||
transliterate('tôi yêu những chú kỳ lân');
|
||||
//=> 'toi yeu nhung chu ky lan'
|
||||
|
||||
transliterate('En–dashes and em—dashes are normalized');
|
||||
//=> 'En-dashes and em-dashes are normalized'
|
||||
```
|
||||
*/
|
||||
export default function transliterate(string: string, options?: Options): string;
|
||||
+129
@@ -0,0 +1,129 @@
|
||||
import builtinReplacements from './replacements.js';
|
||||
import localeReplacements, {localeContextReplacements} from './locale-replacements.js';
|
||||
|
||||
// TODO: Use Regex.escape when targeting Node.js 24.
|
||||
const escapeRegex = string => string.replaceAll(/[$\(\)*+.?\[\\\]^\{\|\}]/gv, String.raw`\$&`);
|
||||
|
||||
const buildReplacementPattern = replacements => {
|
||||
// Sort by key length descending so longer patterns match first (e.g., 'ու' before 'ո')
|
||||
const sortedKeys = replacements.keys().toArray().toSorted((a, b) => b.length - a.length);
|
||||
return new RegExp(sortedKeys.map(key => escapeRegex(key)).join('|'), 'gv');
|
||||
};
|
||||
|
||||
// A locale only changes the value of keys that are already in the built-in table, so every locale matches the same characters and can share one pre-compiled pattern. Only the replacement values differ.
|
||||
const pattern = buildReplacementPattern(builtinReplacements);
|
||||
|
||||
const defaultLocaleData = {
|
||||
replacements: builtinReplacements,
|
||||
contextReplacements: [],
|
||||
};
|
||||
|
||||
const localeCache = new Map();
|
||||
|
||||
const getLocaleData = locale => {
|
||||
if (locale === undefined) {
|
||||
return defaultLocaleData;
|
||||
}
|
||||
|
||||
let data = localeCache.get(locale);
|
||||
if (data === undefined) {
|
||||
data = {
|
||||
replacements: new Map([...builtinReplacements, ...localeReplacements[locale]]),
|
||||
contextReplacements: localeContextReplacements[locale] ?? [],
|
||||
};
|
||||
localeCache.set(locale, data);
|
||||
}
|
||||
|
||||
return data;
|
||||
};
|
||||
|
||||
const normalizeLocale = locale => {
|
||||
if (!locale) {
|
||||
return;
|
||||
}
|
||||
|
||||
const normalizedLocale = locale.toLowerCase()
|
||||
// The Norwegian codes `no` (generic) and `nn` (Nynorsk) use the Bokmål (`nb`) rules
|
||||
.replace(/^(?:no|nn)(?<suffix>-|$)/v, 'nb$<suffix>');
|
||||
|
||||
if (Object.hasOwn(localeReplacements, normalizedLocale)) {
|
||||
return normalizedLocale;
|
||||
}
|
||||
|
||||
const prefix = normalizedLocale.split('-', 1)[0];
|
||||
if (Object.hasOwn(localeReplacements, prefix)) {
|
||||
return prefix;
|
||||
}
|
||||
};
|
||||
|
||||
const normalize = (string, form) => {
|
||||
// Long combining-mark sequences can make native normalization take quadratic time.
|
||||
if (/\p{Mark}{101}/v.test(string)) {
|
||||
throw new RangeError('Cannot normalize more than 100 consecutive combining marks');
|
||||
}
|
||||
|
||||
return string.normalize(form);
|
||||
};
|
||||
|
||||
export default function transliterate(string, options) {
|
||||
if (typeof string !== 'string') {
|
||||
throw new TypeError(`Expected a string, got \`${typeof string}\``);
|
||||
}
|
||||
|
||||
const {replacements, contextReplacements} = getLocaleData(normalizeLocale(options?.locale));
|
||||
|
||||
const applyReplacements = input => input.replace(pattern, match => replacements.get(match));
|
||||
|
||||
// Normalize the keys so they match canonically equivalent input
|
||||
const customReplacements = Array.from(options?.customReplacements ?? [], ([key, value]) => [normalize(key), value]);
|
||||
|
||||
// Every replacement key and locale context contains non-ASCII text and the first normalization is a no-op for ASCII, so pure ASCII input can only pass through unchanged. This is the common case for slugs and identifiers.
|
||||
if (customReplacements.length === 0 && !/\P{ASCII}/v.test(string)) {
|
||||
return string;
|
||||
}
|
||||
|
||||
string = normalize(string);
|
||||
|
||||
if (customReplacements.length > 0) {
|
||||
// Apply customReplacements separately (avoids expensive regex compilation)
|
||||
// Sort by key length descending so longer patterns match first
|
||||
customReplacements.sort((a, b) => b[0].length - a[0].length);
|
||||
for (const [key, value] of customReplacements) {
|
||||
// A replacement value containing `$&` or `$1` is expanded by `replaceAll`. This is long-standing behavior, so preserve it.
|
||||
// eslint-disable-next-line unicorn/no-unsafe-string-replacement
|
||||
string = string.replaceAll(key, value);
|
||||
}
|
||||
|
||||
// Custom replacement values can be in any normalization form
|
||||
string = normalize(string);
|
||||
}
|
||||
|
||||
for (const [contextPattern, value] of contextReplacements) {
|
||||
string = string.replaceAll(contextPattern, () => value);
|
||||
}
|
||||
|
||||
// Arabic presentation forms are positional variants of the base letters, so they transliterate like the text they decompose to. This also expands the lam-alef ligatures into two letters.
|
||||
string = string.replaceAll(/[\u{FB50}-\u{FDFF}\u{FE70}-\u{FEFF}]/gv, match => match.normalize('NFKC'));
|
||||
|
||||
string = applyReplacements(string);
|
||||
|
||||
// Every replacement value is ASCII, so a pure ASCII result has nothing left to strip, match, or dash-normalize. This is the common case for Latin and Cyrillic text.
|
||||
if (!/\P{ASCII}/v.test(string)) {
|
||||
return string;
|
||||
}
|
||||
|
||||
// ASCII carets and backticks are classified as diacritics but should remain literal punctuation.
|
||||
// The negation stroke in `≠` is also not an accent, so it is excluded to keep the meaning.
|
||||
// Recompose even when no diacritics were removed, since replacements can introduce a base character that composes with a retained combining mark.
|
||||
const stripped = normalize(normalize(string, 'NFD').replaceAll(/[[\p{Diacritic}--\p{ASCII}]--\u{338}]/gv, ''));
|
||||
|
||||
// Removing diacritics can expose base letters that still need transliteration. No key survives the pass above, so this second pass can only find characters that the stripping just exposed.
|
||||
if (stripped !== string) {
|
||||
string = applyReplacements(stripped);
|
||||
}
|
||||
|
||||
// Normalize all dash types to hyphen-minus. Hyphen-minus itself is excluded, as replacing it with itself is only wasted work.
|
||||
string = string.replaceAll(/[\p{Dash_Punctuation}--\-]/gv, '-');
|
||||
|
||||
return string;
|
||||
}
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (https://sindresorhus.com)
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
+157
@@ -0,0 +1,157 @@
|
||||
/**
|
||||
Language-specific replacement rules.
|
||||
|
||||
Keys are BCP-47 language tags (or their prefixes).
|
||||
|
||||
Values are arrays of [from, to] replacement pairs.
|
||||
|
||||
These replacements take precedence over the default replacements when a matching locale is specified.
|
||||
*/
|
||||
|
||||
// Shared Swedish/Finnish replacements
|
||||
const swedishFinnishReplacements = [
|
||||
['ä', 'a'],
|
||||
['Ä', 'A'],
|
||||
['ö', 'o'],
|
||||
['Ö', 'O'],
|
||||
['å', 'a'],
|
||||
['Å', 'A'],
|
||||
];
|
||||
|
||||
// Shared Danish/Norwegian replacements
|
||||
const danishNorwegianReplacements = [
|
||||
['æ', 'ae'],
|
||||
['Æ', 'Ae'],
|
||||
['ø', 'oe'],
|
||||
['Ø', 'Oe'],
|
||||
['å', 'aa'],
|
||||
['Å', 'Aa'],
|
||||
];
|
||||
|
||||
const localeReplacements = {
|
||||
// Swedish
|
||||
sv: swedishFinnishReplacements,
|
||||
|
||||
// Finnish
|
||||
fi: swedishFinnishReplacements,
|
||||
|
||||
// Danish
|
||||
da: danishNorwegianReplacements,
|
||||
|
||||
// Norwegian Bokmål
|
||||
nb: danishNorwegianReplacements,
|
||||
|
||||
// German
|
||||
de: [
|
||||
['ä', 'ae'],
|
||||
['Ä', 'Ae'],
|
||||
['ö', 'oe'],
|
||||
['Ö', 'Oe'],
|
||||
['ü', 'ue'],
|
||||
['Ü', 'Ue'],
|
||||
['ß', 'ss'],
|
||||
['ẞ', 'Ss'],
|
||||
],
|
||||
|
||||
// Turkish
|
||||
tr: [
|
||||
['â', 'a'],
|
||||
['Â', 'A'],
|
||||
['ö', 'o'],
|
||||
['Ö', 'O'],
|
||||
['ü', 'u'],
|
||||
['Ü', 'U'],
|
||||
],
|
||||
|
||||
// Hungarian
|
||||
hu: [
|
||||
['ű', 'u'],
|
||||
['Ű', 'U'],
|
||||
['ö', 'o'],
|
||||
['Ö', 'O'],
|
||||
['ü', 'u'],
|
||||
['Ü', 'U'],
|
||||
['á', 'a'],
|
||||
['Á', 'A'],
|
||||
['é', 'e'],
|
||||
['É', 'E'],
|
||||
['í', 'i'],
|
||||
['Í', 'I'],
|
||||
['ó', 'o'],
|
||||
['Ó', 'O'],
|
||||
['ú', 'u'],
|
||||
['Ú', 'U'],
|
||||
],
|
||||
|
||||
// Bulgarian (Streamlined System)
|
||||
bg: [
|
||||
['х', 'h'],
|
||||
['Х', 'H'],
|
||||
['щ', 'sht'],
|
||||
['Щ', 'Sht'],
|
||||
['ъ', 'a'],
|
||||
['Ъ', 'A'],
|
||||
['ь', 'y'],
|
||||
['Ь', 'Y'],
|
||||
// The Russian ъе digraph does not apply in Bulgarian.
|
||||
['ъе', 'ae'],
|
||||
['Ъе', 'Ae'],
|
||||
['ъЕ', 'aE'],
|
||||
['ЪЕ', 'AE'],
|
||||
],
|
||||
|
||||
// Serbian
|
||||
sr: [
|
||||
['х', 'h'],
|
||||
['Х', 'H'],
|
||||
['ђ', 'dj'],
|
||||
['Ђ', 'Dj'],
|
||||
['đ', 'dj'],
|
||||
['Đ', 'Dj'],
|
||||
['џ', 'dz'],
|
||||
['Џ', 'Dz'],
|
||||
['љ', 'lj'],
|
||||
['Љ', 'Lj'],
|
||||
['њ', 'nj'],
|
||||
['Њ', 'Nj'],
|
||||
['ћ', 'c'],
|
||||
['Ћ', 'C'],
|
||||
['ч', 'ch'],
|
||||
['Ч', 'Ch'],
|
||||
['ш', 'sh'],
|
||||
['Ш', 'Sh'],
|
||||
['ж', 'zh'],
|
||||
['Ж', 'Zh'],
|
||||
],
|
||||
};
|
||||
|
||||
// Convert all locale replacements to Maps at module load time
|
||||
for (const locale of Object.keys(localeReplacements)) {
|
||||
localeReplacements[locale] = new Map(localeReplacements[locale]);
|
||||
}
|
||||
|
||||
export default localeReplacements;
|
||||
|
||||
// A combining mark belongs to the letter before it, so marks are skipped when checking the end of a word.
|
||||
const wholeWordPattern = word => new RegExp(String.raw`(?<![\p{Letter}\p{Mark}])${word}(?!\p{Mark}*\p{Letter})`, 'gv');
|
||||
const wordEndPattern = word => new RegExp(String.raw`${word}(?!\p{Mark}*\p{Letter})`, 'gv');
|
||||
|
||||
/**
|
||||
Language-specific replacements that depend on the surrounding text.
|
||||
|
||||
Values are arrays of [pattern, replacement] pairs. They are applied after the custom replacements and before the other replacements.
|
||||
*/
|
||||
export const localeContextReplacements = {
|
||||
// Bulgarian
|
||||
bg: [
|
||||
// The country name is a fixed exception (България → Bulgaria, not Balgaria)
|
||||
[wholeWordPattern('България'), 'Bulgaria'],
|
||||
[wholeWordPattern('БЪЛГАРИЯ'), 'BULGARIA'],
|
||||
[wholeWordPattern('българия'), 'bulgaria'],
|
||||
|
||||
// Word-final ия is ia (София → Sofia)
|
||||
[wordEndPattern('ия'), 'ia'],
|
||||
[wordEndPattern('Ия'), 'Ia'],
|
||||
[wordEndPattern('ИЯ'), 'IA'],
|
||||
],
|
||||
};
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
{
|
||||
"name": "@sindresorhus/transliterate",
|
||||
"version": "3.1.0",
|
||||
"description": "Convert Unicode characters to Latin characters using transliteration",
|
||||
"license": "MIT",
|
||||
"repository": "sindresorhus/transliterate",
|
||||
"funding": "https://github.com/sponsors/sindresorhus",
|
||||
"author": "Sindre Sorhus <sindresorhus@gmail.com> (https://sindresorhus.com)",
|
||||
"type": "module",
|
||||
"exports": {
|
||||
"types": "./index.d.ts",
|
||||
"default": "./index.js"
|
||||
},
|
||||
"sideEffects": false,
|
||||
"engines": {
|
||||
"node": ">=22"
|
||||
},
|
||||
"scripts": {
|
||||
"test": "xo && node --test"
|
||||
},
|
||||
"files": [
|
||||
"index.js",
|
||||
"index.d.ts",
|
||||
"locale-replacements.js",
|
||||
"replacements.js"
|
||||
],
|
||||
"keywords": [
|
||||
"transliterate",
|
||||
"transliteration",
|
||||
"string",
|
||||
"deburr",
|
||||
"unicode",
|
||||
"ascii",
|
||||
"text",
|
||||
"latin",
|
||||
"latinize",
|
||||
"convert",
|
||||
"replace"
|
||||
],
|
||||
"devDependencies": {
|
||||
"xo": "^5.0.1"
|
||||
}
|
||||
}
|
||||
+164
@@ -0,0 +1,164 @@
|
||||
# transliterate
|
||||
|
||||
> Convert Unicode characters to Latin characters using [transliteration](https://en.wikipedia.org/wiki/Transliteration)
|
||||
|
||||
Can be useful for [slugification](https://github.com/sindresorhus/slugify) purposes and other times you cannot use Unicode.
|
||||
|
||||
## Install
|
||||
|
||||
```sh
|
||||
npm install @sindresorhus/transliterate
|
||||
```
|
||||
|
||||
## Usage
|
||||
|
||||
```js
|
||||
import transliterate from '@sindresorhus/transliterate';
|
||||
|
||||
transliterate('Fußgängerübergänge');
|
||||
//=> 'Fussgaengeruebergaenge'
|
||||
|
||||
transliterate('Я люблю единорогов');
|
||||
//=> 'Ya lyublyu edinorogov'
|
||||
|
||||
transliterate('أنا أحب حيدات');
|
||||
//=> 'ana ahb hydat'
|
||||
|
||||
transliterate('tôi yêu những chú kỳ lân');
|
||||
//=> 'toi yeu nhung chu ky lan'
|
||||
|
||||
transliterate('En–dashes and em—dashes are normalized');
|
||||
//=> 'En-dashes and em-dashes are normalized'
|
||||
```
|
||||
|
||||
## API
|
||||
|
||||
### transliterate(string, options?)
|
||||
|
||||
Throws a `RangeError` if any string being normalized contains more than 100 consecutive Unicode combining marks. This includes the input, custom replacement keys, and intermediate results. The total string length is not limited.
|
||||
|
||||
#### string
|
||||
|
||||
Type: `string`
|
||||
|
||||
String to transliterate.
|
||||
|
||||
#### options
|
||||
|
||||
Type: `object`
|
||||
|
||||
##### customReplacements
|
||||
|
||||
Type: `Array<[string, string]> | Map<string, string>`\
|
||||
Default: `[]`
|
||||
|
||||
Add your own custom replacements.
|
||||
|
||||
The replacements are run on the original string before any other transformations. Both the string and the keys are normalized to NFC first, so a key matches canonically equivalent text.
|
||||
|
||||
This only overrides a default replacement if you set an item with the same key.
|
||||
|
||||
```js
|
||||
import transliterate from '@sindresorhus/transliterate';
|
||||
|
||||
transliterate('Я люблю единорогов', {
|
||||
customReplacements: [
|
||||
['единорогов', '🦄']
|
||||
]
|
||||
})
|
||||
//=> 'Ya lyublyu 🦄'
|
||||
```
|
||||
|
||||
You can also pass a `Map`:
|
||||
|
||||
```js
|
||||
transliterate('foo & bar', {
|
||||
customReplacements: new Map([
|
||||
['&', 'and']
|
||||
])
|
||||
})
|
||||
//=> 'foo and bar'
|
||||
```
|
||||
|
||||
##### locale
|
||||
|
||||
Type: `string`
|
||||
|
||||
[BCP-47](https://developer.mozilla.org/en-US/docs/Glossary/BCP_47_language_tag) language tag for language-specific transliteration.
|
||||
|
||||
When specified, uses language-specific replacement rules for characters that have different transliterations in different languages.
|
||||
|
||||
```js
|
||||
import transliterate from '@sindresorhus/transliterate';
|
||||
|
||||
// Swedish: ä→a, ö→o, å→a
|
||||
transliterate('Räksmörgås', {locale: 'sv'});
|
||||
//=> 'Raksmorgas'
|
||||
|
||||
// German: ä→ae, ö→oe
|
||||
transliterate('Räksmörgås', {locale: 'de'});
|
||||
//=> 'Raeksmoergas'
|
||||
```
|
||||
|
||||
### Supported locales
|
||||
|
||||
The following locales have specific replacement rules when using the `locale` option:
|
||||
|
||||
- `bg` - Bulgarian
|
||||
- `da` - Danish
|
||||
- `de` - German
|
||||
- `fi` - Finnish
|
||||
- `hu` - Hungarian
|
||||
- `nb` - Norwegian Bokmål
|
||||
- `sr` - Serbian
|
||||
- `sv` - Swedish
|
||||
- `tr` - Turkish
|
||||
|
||||
The `no` and `nn` language codes are aliases for `nb`.
|
||||
|
||||
## Supported languages
|
||||
|
||||
Most major languages are supported.
|
||||
|
||||
This includes special handling for:
|
||||
|
||||
- Arabic
|
||||
- Armenian
|
||||
- Belarusian
|
||||
- Bulgarian
|
||||
- Croatian
|
||||
- Czech
|
||||
- Danish
|
||||
- Dhivehi
|
||||
- Finnish
|
||||
- Georgian
|
||||
- German (umlauts)
|
||||
- Greek
|
||||
- Hungarian
|
||||
- Kazakh
|
||||
- Kurdish
|
||||
- Latin
|
||||
- Latvian
|
||||
- Lithuanian
|
||||
- Macedonian
|
||||
- Pashto
|
||||
- Persian
|
||||
- Polish
|
||||
- Romanian
|
||||
- Russian
|
||||
- Serbian
|
||||
- Sindhi
|
||||
- Slovak
|
||||
- Slovenian
|
||||
- Swedish
|
||||
- Tatar
|
||||
- Turkish
|
||||
- Ukrainian
|
||||
- Urdu
|
||||
- Vietnamese
|
||||
|
||||
However, Chinese is [currently not supported](https://github.com/sindresorhus/transliterate/issues/1).
|
||||
|
||||
## Related
|
||||
|
||||
- [slugify](https://github.com/sindresorhus/slugify) - Slugify a string
|
||||
+3375
File diff suppressed because it is too large.
Load diff
Reference in new issue
Block a user