📝
Dartの英数字のStringを全角か半角化する
全角と半角は 65248
を足すか引くかだけなので以下の extension をコピペしたらすぐ使えます
const _fullLengthCode = 65248;
extension JapaneseString on String {
String alphanumericToFullLength() {
final regex = RegExp(r'^[a-zA-Z0-9]+$');
final string = runes.map<String>((rune) {
final char = String.fromCharCode(rune);
return regex.hasMatch(char)
? String.fromCharCode(rune + _fullLengthCode)
: char;
});
return string.join();
}
String alphanumericToHalfLength() {
final regex = RegExp(r'^[A-Za-z0-9]+$');
final string = runes.map<String>((rune) {
final char = String.fromCharCode(rune);
return regex.hasMatch(char)
? String.fromCharCode(rune - _fullLengthCode)
: char;
});
return string.join();
}
}
Discussion