Skip to content

Instantly share code, notes, and snippets.

@mathewthe2
Created Aug 31, 2021
Embed
What would you like to do?
Converts Anki styled Furigana to Ruby style in React
import { Fragment } from 'react'
export const formatFurigana = (sentenceId, sentence) => {
// sentenceId is used for the unique keys for each of the Furigana and Kanji text components
if (sentence === undefined) {
return ''
}
let compiled_list = []
let text = '';
let parsing_furigana = false;
let finding_kanji = false;
let furigana = '';
let kanji = '';
let start;
for (let i = sentence.length-1; i >= 0; i--) {
if (sentence[i] === ']') {
start = i;
parsing_furigana = true;
if (text.length > 0) {
compiled_list.unshift({
furigana: text,
kanji: ''
})
text = '';
}
} else if (sentence[i] === '[') {
parsing_furigana = false;
finding_kanji = true;
} else if (parsing_furigana) {
furigana = sentence[i] + furigana;
} else if (finding_kanji) {
if (i === 0 || sentence[i] === ' ') {
kanji = sentence[i] + kanji;
compiled_list.unshift({
furigana: furigana,
kanji: kanji
})
furigana = '';
kanji = '';
finding_kanji = false;
} else {
kanji = sentence[i] + kanji;
}
} else {
text = sentence[i] + text;
}
}
compiled_list.unshift({
furigana: text,
kanji: ''
})
return (
compiled_list.map((item, index)=>(
item.kanji.length > 0 ?
<ruby key={`example_${sentenceId}_item${index}`}>
{item.kanji}
<rt style={{WebkitUserSelect: 'none'}}>{item.furigana}</rt>
</ruby>
:
<Fragment key={`example_${sentenceId}_item${index}`}>
{item.furigana}
</Fragment>
))
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment