8
3

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 3 years have passed since last update.

【Javascript・GAS】文字列から記号を取り除きたい時

Last updated at Posted at 2020-03-16

コピペで使えるようにしました.(※追記もみてください><)

function remove() {
  const str = "ABC,.~!@#$%^&*()_+{}[]:;\"'<>?\\/|DE";
  const replaced = str.replace(/[,\.~!@#\$%\^&\*\(\)_\+\-=\{\}\[\]:;"'<>?\\\/\|]/g, '');
  console.log(replaced); // "ABCDE"
}

全角も含むならこんな感じです.

function remove() {
  const str = "【】『』A,B.・;’「」`\C,.~!@#$%^&*()_+{}[]:;\"'<>?\\/|DE";
  const replaced = str.replace(/[【】『』,.・;’「」`\,\.~!@#\$%\^&\*\(\)_\+\-=\{\}\[\]:;"'<>?\\\/\|]/g, '');
  console.log(replaced); // "ABCDE"
}

記号は無限にあるので必要があれば随時追加してください.

追記

よく考えたら以下のもの以外と指定した方が安全でした.

  • ひらがな
  • カタカナ
  • 漢字
  • アルファベット
  • 数字

すると以下のようになります.

function remove() {
  const const str = "あA_!A・1";
  const replaced = str.replace(/[^0-9A-Za-z\u3041-\u3096\u30A1-\u30F6\u3005-\u3006\u3400-\u3fff]/g, '');
  console.log(replaced); // "あAA1"
}

UTF-8の番号はこのサイトを参考にしました.

8
3
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
8
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?