6
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【JavaScript】半角カタカナ⇒全角カタカナの変換

Last updated at Posted at 2020-07-23

#最初に

タイトル通り、半角カタカナを全角カタカナへ変換します。

今更な内容ですが自分が採用している書き方を載せます。
どちらかといえば長文の文字列向け?

短い文字列でも遅くなりすぎるという事はないと思います。

#1.String.prototypeを拡張

if(!String.prototype.toZenKata) {
	String.prototype.toZenKata = function () {
		//muddy
		var dm = 'ガギグゲゴザジズゼゾダヂヅデドバビブベボパピプペポヴヷヺ';
		var sm = 'ガギグゲゴザジズゼゾダヂヅデドバビブベボパピプペポヴヷヺ';
		//kiyone
		var dk = 'アイウエオカキクケコサシスセソタチツテトナニヌネノハヒフヘホ'
				+'マミムメモヤユヨラリルレロワヲンァィゥェォッャュョ。、ー「」・';
		var sk = 'アイウエオカキクケコサシスセソタチツテトナニヌネノハヒフヘホマミムメモヤユヨラリルレロワヲンァィゥェォッャュョ。、ー「」・';
		
		var str = this;
		for (var i=0,len=dm.length; i<len; i++) {
			str = str.split( sm.slice(i*2, i*2+2) ).join( dm.slice(i, i+1) );
		}
		for (var i=0,len=dk.length; i<len; i++) {
			str = str.split( sk.slice(i, i+1) ).join( dk.slice(i, i+1) );
		}
		return str;
	};
}

const text = 'ダヂヅデドダヂヅデドダヂヅデド';
console.log( text.toZenKata() );	//result => ダヂヅデドダヂヅデドダヂヅデド

#2.普通に関数で

//muddy
const D_MUD = 'ガギグゲゴザジズゼゾダヂヅデドバビブベボパピプペポヴヷヺ';
const S_MUD = 'ガギグゲゴザジズゼゾダヂヅデドバビブベボパピプペポヴヷヺ';
//kiyone
const D_KIY = 'アイウエオカキクケコサシスセソタチツテトナニヌネノハヒフヘホ'
			+'マミムメモヤユヨラリルレロワヲンァィゥェォッャュョ。、ー「」・';
const S_KIY = 'アイウエオカキクケコサシスセソタチツテトナニヌネノハヒフヘホマミムメモヤユヨラリルレロワヲンァィゥェォッャュョ。、ー「」・';
	
const toZenKata = str => {
	for (let i=0,len=D_MUD.length; i<len; i++) {
		str = str.split( S_MUD.slice(i*2, i*2+2) ).join( D_MUD.slice(i, i+1) );
	}
	for (let i=0,len=D_KIY.length; i<len; i++) {
		str = str.split( S_KIY.slice(i, i+1) ).join( D_KIY.slice(i, i+1) );
	}
	return str;
};

const text = 'ダヂヅデドダヂヅデドダヂヅデド';
console.log( toZenKata( text ) );	//result => ダヂヅデドダヂヅデドダヂヅデド

1と違い一部外に置いたのは、どちらに置くのがベストか私がいまいち理解できてないからです。

#最後に

長い文字列を扱うケースはあまりないかもしれませんね…

6
4
6

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?