Converting Texts to Bold, Italic and Bold-Italic Types of Unicode using Google Apps Script

Gists

This is a sample script for converting the texts to the bold, italic, bold-italic types, underline and strike through of the unicode using Google Apps Script. In the current stage, at Google Docs (Spreadsheet, Document, Slides and so on), the rich texts cannot be directly managed for all places using Google Apps Script. But there are the places which can use the bold, italic and bold-italic fonts with the unicode. This sample script uses this. When this sample script is used, for example, the bold, italic and bold-italic texts can be put using SpreadsheetApp.getUi().alert(convertedText).

Sample script

const conv = {
  c: function (text, obj) {
    return text.replace(
      new RegExp(`[${obj.reduce((s, { r }) => (s += r), "")}]`, "g"),
      (e) => {
        const t = e.codePointAt(0);
        if (
          (t >= 48 && t <= 57) ||
          (t >= 65 && t <= 90) ||
          (t >= 97 && t <= 122)
        ) {
          return obj.reduce((s, { r, d }) => {
            if (new RegExp(`[${r}]`).test(e))
              s = String.fromCodePoint(e.codePointAt(0) + d);
            return s;
          }, "");
        }
        return e;
      }
    );
  },
  bold: function (text) {
    return this.c(text, [
      { r: "0-9", d: 120734 },
      { r: "A-Z", d: 120211 },
      { r: "a-z", d: 120205 },
    ]);
  },
  italic: function (text) {
    return this.c(text, [
      { r: "A-Z", d: 120263 },
      { r: "a-z", d: 120257 },
    ]);
  },
  boldItalic: function (text) {
    return this.c(text, [
      { r: "A-Z", d: 120315 },
      { r: "a-z", d: 120309 },
    ]);
  },
  underLine: function (text) {
    return text.length > 0 ? [...text].join("\u0332") + "\u0332" : "";
  },
  strikethrough: function (text) {
    return text.length > 0 ? [...text].join("\u0336") + "\u0336" : "";
  },
};

// Please run this function.
function main() {
  var text = "Sample value 123\nSample value 456\nSample value 789";
  console.log(text); // Original text
  console.log(conv.bold(text)); // Bold type
  console.log(conv.italic(text)); // Italic type
  console.log(conv.boldItalic(text)); // Bold-italic type
  console.log(conv.underLine(text)); // Underline
  console.log(conv.strikethrough(text)); // Strikethrough
}

Testing

https://jsfiddle.net/xokujwh1/

Note

  • In this case, the numbers and the specific characters have no italic and bold-italic types. Please be careful this.
  • This can be also used with Javascript.

References

 Share!