Skip to content

Instantly share code, notes, and snippets.

@choyno
Last active October 13, 2023 02:36
Show Gist options
  • Save choyno/01c827e069c698cc5447dad8acf39d07 to your computer and use it in GitHub Desktop.
Save choyno/01c827e069c698cc5447dad8acf39d07 to your computer and use it in GitHub Desktop.
Full Width and Half Width Counter
Step 1 Import to react Component
```import useFullWidthChecker from '../../../../../hooks/helper/useFullWidthChecker';```
Step 2 Call the Function
``` const { characterCounter } = useFullWidthChecker();```
Step 3 Run Function
``` console.log(characterCounter(:TEXT COUNTER HERRE ));```
Results
```https://app.screencast.com/jj2B9CJVi6PAR```
Reference sample
Calculate one half-width character as one character
"abcdefg" // 7 characters
Assuming 2 double-byte characters
"ABCDEFG" // 14 characters
Mixed case
"ABCDEFGabcdefg" // 21 characters
Example JP
"豊洲5丁目オフィスビル新築プロジェクト" // 37char
"500ページに及ぶ百科事典" // 23char
const useFullWidthChecker = () => {
const isFullWidth = (char: string) => {
const code = char.charCodeAt(0);
const fullWidthRegex = /[\u3000-\uFFEF]/;
// These are some common ranges for full-width characters. You might need to adjust based on your requirements.
return (code >= 0x1100 && code <= 0x115F) || // Hangul Jamo
(code >= 0x2E80 && code <= 0x9FFF) || // CJK ideographs, Hiragana, Katakana, etc.
(code >= 0xAC00 && code <= 0xD7AF) || // Hangul Syllables
(code >= 0xF900 && code <= 0xFAFF) || // CJK Compatibility Ideographs
(code >= 0xFE30 && code <= 0xFE4F) || // CJK Compatibility Forms
(fullWidthRegex.test(char)); // English Alphabet
};
const characterCounter = (checkChar: string) => {
let fullCount = 0;
let halfCount = 0;
for (let char of checkChar) {
if (isFullWidth(char)) {
fullCount += 2;
} else {
halfCount += 1;
}
}
return fullCount + halfCount;
}
return {
characterCounter
};
};
export default useFullWidthChecker;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment