3
4

More than 3 years have passed since last update.

Node.js基礎:文字列処理

Last updated at Posted at 2020-04-19

はじめに

文字列の処理はもっとも使う処理です。Node.jsの文字列処理をまとめてみます。

基本:シングル、ダブルクォーテーションで囲んで定義

sample.js
// 単一行
const str1 = "abc";

// 複数行
const str2 = `あいうえお
かきくけこ
はひふひほ`

// 複数行: +で連結
const str3 = "abc" + "\n" + "def";

// シングルクォーテーションで囲んで定義
const str4 = 'あいうえお' + '\n' + 'かきくけこ';

// 変数置換
const tempStr = "abc";
const str = `tempStr=${tempStr}`

文字列処理メソッド

説明ページ:https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Global_Objects/String

  • String.prototype.startsWith()
  • String.prototype.endsWith()
  • String.prototype.split()
  • String.prototype.replace()
  • String.prototype.indexOf()
  • String.prototype.toLowerCase()
  • String.prototype.toUpperCase()
  • String.prototype.trim()
  • String.prototype.charAt()
  • String.fromCharCode()

など。用意されているメソッドがたくさんあります。

Bufferクラス

Node.jsの中ではBufferを使って文字列処理のメソッドもたくさんあります。
説明ページ:https://nodejs.org/api/buffer.html

例:

node.js
const buf = Buffer.from('こんにちは!', 'utf8');

console.log(buf.toString('hex'));
// e38193e38293e381abe381a1e381afefbc81
console.log(buf.toString('base64'));
// 44GT44KT44Gr44Gh44Gv77yB

util.format(format[, ...args])

文字列のフォーマットもよく使う処理です。

例:

node.js
const util = require("util")

const f1 = util.format('%s ,%d, %i, %f, %j, %o, %O', 'foo', -1234, 01, 3.14, {a : "a", "b" : "b"}, {a: 10}, [1 ,2 ,3]);
console.log(f1)
//foo ,-1234, 1, 3.14, {"a":"a","b":"b"}, { a: 10 }, [ 1, 2, 3 ]

説明ページ:https://nodejs.org/api/util.html#util_util_format_format_args

util.TextEncoderクラス

文字列をUint8Array 配列に変換

node.js
const {TextEncoder} = require("util")

const encoder = new TextEncoder();
const uint8array = encoder.encode('こんにちは!\n Hello World!'); // UTF-8のみサポート

console.log(uint8array);

/*Uint8Array [
  116,
  104,
  105,
  115,
  32,
  105,
  115,
  32,
  115,
  111,
  109,
  101,
  32,
  100,
  97,
  116,
  97 ]*/

util.TextDecoderクラス

Uint8Array配列を文字列に変換。

例:

node.js
const {TextEncoder, TextDecoder} = require("util")

const encoder = new TextEncoder();
const uint8array = encoder.encode('こんにちは!\n Hello World!');

const originStr = new TextDecoder().decode(uint8array); //UTF-8
console.log(originStr)
/*
こんにちは!
 Hello World!
*/

URLSearchParamsクラス

URLのパラメータ処理も文字列関連ですが、URLSearchParamsを使うと処理しやすいです。
説明ページ:https://nodejs.org/api/url.html#url_class_urlsearchparams

例:

node.js
// 文字列からURLSearchParamsを生成
const params = new URLSearchParams('a=bar&b=baz');

// 配列から
const params2 = new URLSearchParams([
  ['user', 'abc'],
  ['query', 'second']
]);

// MapからURLSearchParamsを生成
const map = new Map();
map.set('user', 'abc');
map.set('query', 'xyz');
const params3 = new URLSearchParams(map);

// パラメータすべて出力
for (const name of params.keys()) {
  console.log(name);
}

// 項目名で取得
const a= params.get('a');

// 項目を追加
params.append('newParam', 'new');

// 項目値を置換
params.set('b', 'bbbbb');

// 項目は存在するかをチェック
console.log(params.has('b'));

// 項目を削除
params.delete('a');

// 文字列で出力
console.log(params.toString());
/*
b=bbbbb&newParam=new
*/

以上

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