Search code examples
reactjsgatsby

Transliteration of links Gatsby JS


Who knows how to transliterate links on the go? I have a website being developed on Gatsby. I'm creating a category for a post there, writing it in frontmatter. Some categories can be written in Cyrillic.

---
title: "Yet Another Post"
date: "2021-07-25"
slug: "yet-another-post"
tags: ["animals", "Chicago", "zoos"]
categories: ["GatsbyJS", "Gatsby Develop", "Сайт с нуля"]
featuredImage: "./third.jpg"
---

Then in your gatsby-node.js I am creating a page for this category (I use a kebab case, since the url is formed from the category name)

 createPage({
        path: `blog/category/${_.kebabCase(category)}`,
        component: require.resolve("./src/templates/categories.js"),

As a result, it turns out that the link to the page of the category "Сайт с нуля" ("Site from scratch" for eng) will look like www.domain.ru/blog/category/сайт-с-нуля, and I would like to have transliteration of links, for example www.domain.ru/blog/category/sait-s-nulya. Is it possible?


Solution

  • You can use a mapping helper function like:

    const letters = {"Ё":"YO","Й":"I","Ц":"TS","У":"U","К":"K","Е":"E","Н":"N","Г":"G","Ш":"SH","Щ":"SCH","З":"Z","Х":"H","Ъ":"'","ё":"yo","й":"i","ц":"ts","у":"u","к":"k","е":"e","н":"n","г":"g","ш":"sh","щ":"sch","з":"z","х":"h","ъ":"'","Ф":"F","Ы":"I","В":"V","А":"a","П":"P","Р":"R","О":"O","Л":"L","Д":"D","Ж":"ZH","Э":"E","ф":"f","ы":"i","в":"v","а":"a","п":"p","р":"r","о":"o","л":"l","д":"d","ж":"zh","э":"e","Я":"Ya","Ч":"CH","С":"S","М":"M","И":"I","Т":"T","Ь":"'","Б":"B","Ю":"YU","я":"ya","ч":"ch","с":"s","м":"m","и":"i","т":"t","ь":"'","б":"b","ю":"yu"};
    
    function transliterate(slug) {
      return slug
        .split("")
        .map((char) => letters[char] || char)
        .join("");
    }
    
    
    console.log(transliterate("www.domain.ru/blog/category/сайт-с-нуля"))

    Modified from transliterating cyrillic to latin with javascript function

    Applied to your case:

     createPage({
            path: `blog/category/${_.kebabCase(transliterate(category))}`,
            component: require.resolve("./src/templates/categories.js"),