LANG SELRCT

Apps Script Reference  (Create: Create new Spreadsheet | Create new Apps Script

Saturday, May 9, 2020

console.logを%cで区切るとスタイルを適用できる


console.logで出力するメッセージを装飾したい場合


この例ではmessageを青色にしています。

ポイント

  • %cで区切った後のテキストに対して、その次の引数でスタイルを設定できる


console.log("Console %cmessage", "color: blue;");



コード.gs
function doGet() {
  return HtmlService.createHtmlOutputFromFile("index");
}
意訳
この機能がやること
指定したHTMLファイルを表示する




index.html
<!DOCTYPE html>
<html>
<body>
<script>

console.log("Console %cmessage", "color: blue;");

</script>
</body>
</html>



補足


書き方のパターンをいくつか試してみました。


index2.html
<!DOCTYPE html>
<html>
<body>
<script>

consoleStyled();
function consoleStyled() {

  // 一行で書く場合
  console.log("Console %cmessage", "color: white; background-color: blue;");
  
  // 代入する場合
  var color = "color: blue;";
  console.log("Console %cmessage", color);
  
  // 複数を配列で用意してjoinして代入する場合
  var props = [
    "color: white",
    "background-color: blue",
    "padding: 2px",
    "font-size: 15px"
  ];
  var style = props.join("; ");
  console.log("Console %cmessage", style);
 
  // 異なるスタイルを適用する場合はさらに%cで区切って、引数にスタイルを追加する
  console.log("Console %cmessage %cgreen", "color: blue;", "color: green");
}

</script>
</body>
</html>



Latest post

Extracting data from Google Sheets with regular expressions

Introduction Regular expressions are a powerful tool that can be used to extract data from text.  In Google Sheets, regular expressions ca...