how to put string that contains japanese character conditionally into separate arrays in Javascript

Viewed 243

I just asked how to put string conditionally into separate arrays in Javascript and it gave me a great hint, but could not fix my actual problem.

I asked as alphabet and number to simplify my question but actual string contains 2 types of Japanese character: kanji and hiragana.

Do you think do same thing as the answer in the previous question somewhat? I will leave examples here

(example 1)

string: 生き残る (生, 残 => kanji き, る => hiragana)

result: [生],[き],[残],[る]

(example 2)

string: 楽しい (楽 => kanji しい => hiragana)

result: [楽],[しい]


and this is what I tried (and failed)

let regexForKanji = /([\u{3005}\u{3007}\u{303b}\u{3400}-\u{9FFF}\u{F900}-\u{FAFF}\u{20000}-\u{2FFFF}][\u{E0100}-\u{E01EF}\u{FE00}-\u{FE02}]?)/mu

let regexForHiragana = /[\u{3000}-\u{301C}\u{3041}-\u{3093}\u{309B}- \u{309E}]/mu



let string = "生き残る"

function ja2Bit ( str ) {
  return ( str.match(`${hiragana}+|${kanji}`)) 
}

ja2Bit(string)

//VM534193:2 Uncaught SyntaxError: Invalid regular expression: //[\u{3000}-\u{301C}\u{3041}-\u{3093}\u{309B}-\u{309E}]/mu+|/([\u{3005}\u{3007}\u{303b}\u{3400}-\u{9FFF}\u{F900}-\u{FAFF}\u{20000}-\u{2FFFF}][\u{E0100}-\u{E01EF}\u{FE00}-\u{FE02}]?)/mu/: Range out of order in character class

sorry for asking multiple times. Thanks guys.


update

ok I found solution, and it will work for hiragana, kanji, and karakana as well! Thanks guys for help!

solution

'生き残りタイのか'.match(/^[\u30a0-\u30ff]+|[\u3040-\u309f]+|[\u30e0-\u9fcf]+|[\u30a0-\u30ff]+|[\u3040-\u309f]+/g)
//["生", "き", "残", "り", "タイ", "のか"]
2 Answers
'生き残りタイのか'.match(/^[\u30a0-\u30ff]+|[\u3040-\u309f]+|[\u30e0-\u9fcf]+|[\u30a0-\u30ff]+|[\u3040-\u309f]+/g)
//["生", "き", "残", "り", "タイ", "のか"]

You can use regex.

This should give you a place to start, but I would use regexr and tweak the below to fit your needs.

/[一-龠]+|[ぁ-ゔ]+|[ァ-ヴー]+|[a-zA-Z0-9]+|[a-zA-Z0-9]+|[々〆〤]+/u
let string = "生き残る";

function ja2Bit(str) {
    const kanji = /[\u4E00-\u9FFF]/mu;
    const hiragana = /[\u3040-\u309Fー]/mu;
    if (str.match(kanji)) {
        return `${str} is kanji`;
    } else if (str.match(hiragana)) {
        return `${str} is hiragana`;
    } else {
        return "I don't know";
    }
}

ja2Bit(string);

https://regexr.com/

Related