Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <div id="expression" class="font-big">
- <a href="https://jisho.org/search/{{front}}">{{edit:front}}</a>
- </div>
- <div class="font-smaller">
- {{edit:Hint}}
- </div>
- <div id="hintSentence" class="font-small" style="display: none">
- {{#Sentence}}
- <br><br>
- {{edit:Sentence}}
- {{/Sentence}}
- </div>
- <script>
- (function () {
- // prevent loading front js on back side of card
- if (document.getElementById('answer')) {
- return;
- }
- const expression = '{{front}}';
- const furigana = '{{Reading}}';
- const kanjiRegex = /[\u4e00-\u9faf]/g;
- // if vocab word isn't kanji add hint sentence
- if (!expression.match(kanjiRegex)) {
- const hintSentence = document.getElementById('hintSentence');
- hintSentence.style.display = 'block';
- const sentenceElement = document.querySelector('#hintSentence a');
- highlightWord(sentenceElement, expression, furigana);
- }
- })();
- // run on sentence regardless of having highlight or not
- function highlightWord(sentenceElement, expression, furigana) {
- const sentence = sentenceElement.innerHTML;
- // replace html tags in link
- const href = decodeURIComponent(sentenceElement.getAttribute('href'));
- sentenceElement.href = href.replace(/<[^>]*>/g, '');
- if (!sentence.match('<strong>')) {
- let replace = expression;
- // shorten kanji expression
- replace = shorten(replace, sentence, 1);
- // try furi if kanji didnt work
- replace = sentence.match(replace) ? replace : shorten(furigana, sentence, 2);
- // try katakana
- replace = sentence.match(replace)
- ? replace
- : shorten(hiraganaToKatakana(furigana), sentence, 2);
- sentenceElement.innerHTML = sentenceElement.innerHTML.replace(
- new RegExp(replace, 'g'),
- `<strong>${replace}</strong>`
- );
- }
- }
- // takes an expression and shortens it until it's in the sentence
- function shorten(expression, sentence, minLength) {
- while (expression.length > minLength && !sentence.match(expression)) {
- expression = expression.substr(0, expression.length - 1);
- }
- return expression;
- }
- function hiraganaToKatakana(hiragana) {
- return hiragana.replace(/[\u3041-\u3096]/g, function (c) {
- return String.fromCharCode(c.charCodeAt(0) + 0x60);
- });
- }
- </script>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement