はじめに
文字列の処理はもっとも使う処理です。Node.jsの文字列処理をまとめてみます。
基本:シングル、ダブルクォーテーションで囲んで定義
sample.js
// 単一行conststr1="abc";// 複数行conststr2=`あいうえお
かきくけこ
はひふひほ`// 複数行: +で連結conststr3="abc"+"\n"+"def";// シングルクォーテーションで囲んで定義conststr4='あいうえお'+'\n'+'かきくけこ';
文字列処理メソッド
説明ページ: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
constbuf=Buffer.from('こんにちは!','utf8');console.log(buf.toString('hex'));// e38193e38293e381abe381a1e381afefbc81console.log(buf.toString('base64'));// 44GT44KT44Gr44Gh44Gv77yB
util.format(format[, ...args])
文字列のフォーマットもよく使う処理です。
例:
node.js
constutil=require("util")constf1=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")constencoder=newTextEncoder();constuint8array=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")constencoder=newTextEncoder();constuint8array=encoder.encode('こんにちは!\n Hello World!');constoriginStr=newTextDecoder().decode(uint8array);//UTF-8console.log(originStr)/*
こんにちは!
Hello World!
*/
URLSearchParamsクラス
URLのパラメータ処理も文字列関連ですが、URLSearchParamsを使うと処理しやすいです。
説明ページ:https://nodejs.org/api/url.html#url_class_urlsearchparams
例:
node.js
// 文字列からURLSearchParamsを生成constparams=newURLSearchParams('a=bar&b=baz');// 配列からconstparams2=newURLSearchParams([['user','abc'],['query','second']]);// MapからURLSearchParamsを生成constmap=newMap();map.set('user','abc');map.set('query','xyz');constparams3=newURLSearchParams(map);// パラメータすべて出力for(constnameofparams.keys()){console.log(name);}// 項目名で取得consta=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
*/
以上