3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【GAS】全角英数字、スペースなどを半角に置換する

Last updated at Posted at 2023-01-28

概要

環境: V8 ランタイム

備忘録。

全角英数字を絶対に許さないスクリプトです。書籍APIで取ってきた情報が全角と半角の混合で美しくなかったので、どちらかに統一してしまおうという試み。スペースとコンマはreplaceに渡して半角に置換。

全角文字列を引数に渡せば半角文字列を戻り値で返してくれます。

コード

// 英数字を全角から半角に変換
function convertCharacters(original) {
  let converted = ""; // 空の変数
  const pattern = /[A-Za-z0-9]/; // 全角英数のパターンを用意
  for (let i = 0; i < original.length; i++) { // 受け取った文字列の数だけ繰り返し
    if (pattern.test(original[i])) { // 文字が全角英数のとき
      const half = String.fromCharCode(original[i].charCodeAt(0) - 65248); // 半角英数に変換
      converted += half;
    } else {
      converted += original[i];
    }
  }
  converted = converted.replace(/ /g, ' ').replace(/./g, '.'); // gオプションで該当文字列をすべて置換
  // Logger.log(converted);
  return converted;
}
3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?