JavaScriptの正規表現は、Perlのそれとほぼ同じです。
一致した箇所を配列として返す
sample.js
var str = "This is a string.";
var arr = str.match(/is/g);
console.log(arr);
実行例
$ node sample.js
[ 'is', 'is' ]
正規表現のパターンを変数で用意しておく
sample.js
var pattern = /is/g;
// var pattern = new RegExp("is", 'g'); // 同じ意味
var str = "This is a string.";
var arr = str.match(pattern);
console.log(arr);
実行例
$ node sample.js
[ 'is', 'is' ]
マッチした個数
sample.js
var str = "This is a string.";
console.log(str.search(/is/));
実行例
$ node sample.js
2
置換
sample.js
var str = "This is a string.";
var replaced = str.replace(/is/g, "**");
console.log(str);
console.log(replaced);
実行例
$ node sample.js
This is a string.
Th** ** a string.
一致した箇所を参照
sample.js
var str = "This is a string.";
str = str.replace(/(is)/g, "[$1]");
console.log(str);
実行例
$ node sample.js
Th[is] [is] a string.
0
PythonとJavaScriptがメイン。サーバーレスとマイクロサービスが好き。
記事の執筆者にステッカーを贈る
有益な情報に対するお礼として、またはコメント欄における質問への返答に対するお礼として、 記事の読者は、執筆者に有料のステッカーを贈ることができます。
さらに詳しく →Feedbacks
ログインするとコメントを投稿できます。



