summaryrefslogtreecommitdiff
path: root/packages/misskey-js/src/nyaize.ts
blob: d5ee54776f4e9f85cb560f745cc7b291fa6cf1a6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
/*
 * SPDX-FileCopyrightText: syuilo and misskey-project
 * SPDX-License-Identifier: AGPL-3.0-only
 */

const koRegex1 = /[나-낳]/g;
const koRegex2 = /(다$)|(다(?=\.))|(다(?= ))|(다(?=!))|(다(?=\?))/gm;
const koRegex3 = /(야(?=\?))|(야$)|(야(?= ))/gm;

function ifAfter(prefix: string, fn: (x: string) => string) {
	const preLen = prefix.length;
	const regex = new RegExp(prefix, 'i');
	return (x: string, pos: number, string: string) => {
		return pos > 0 && string.substring(pos - preLen, pos).match(regex) ? fn(x) : x;
	};
}

export function nyaize(text: string): string {
	return text
		// ja-JP
		.replaceAll('な', 'にゃ').replaceAll('ナ', 'ニャ').replaceAll('ナ', 'ニャ')
		// en-US
		.replace(/a/gi, ifAfter('n', x => x === 'A' ? 'YA' : 'ya'))
		.replace(/ing/gi, ifAfter('morn', x => x === 'ING' ? 'YAN' : 'yan'))
		.replace(/one/gi, ifAfter('every', x => x === 'ONE' ? 'NYAN' : 'nyan'))
		// ko-KR
		.replace(koRegex1, match => !isNaN(match.charCodeAt(0)) ? String.fromCharCode(
			match.charCodeAt(0) + '냐'.charCodeAt(0) - '나'.charCodeAt(0),
		) : match)
		.replace(koRegex2, '다냥')
		.replace(koRegex3, '냥');
}