「JavaScript」RegExp.prototype.global のプロパティ属性の使い方

構文
var 変数名 = new RegExp('文字列’, 'g’);
対象文字列.replace(変数名, ");
global プロパティは “g" フラグが正規表現で使われているかどうかを返します。
global の値は Boolean です。 true は “g" フラグを使用していることを表します。
それ以外は false になります。 “g" フラグは、その正規表現が文字列の中で一致する可能性がある場所すべてについてテストを行うことを示します。

使用例

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
var regex = new RegExp('toto', 'g');
console.log(regex.global);
var str = 'toto東京toto';
var resA = str.replace(regex, '');
console.log("gフラグを使用して一致文字列をすべて置換: "+resA);
var regex1 = new RegExp('toto');
var resB = str.replace(regex1, '');
console.log("gフラグを使用しない1つの文字列を置換結果: "+resB);
var regex = new RegExp('toto', 'g'); console.log(regex.global); var str = 'toto東京toto'; var resA = str.replace(regex, ''); console.log("gフラグを使用して一致文字列をすべて置換: "+resA); var regex1 = new RegExp('toto'); var resB = str.replace(regex1, ''); console.log("gフラグを使用しない1つの文字列を置換結果: "+resB);
var regex = new RegExp('toto', 'g');

console.log(regex.global); 

var str = 'toto東京toto';

var resA = str.replace(regex, '');

console.log("gフラグを使用して一致文字列をすべて置換: "+resA);  

var regex1 = new RegExp('toto');

var resB = str.replace(regex1, '');

console.log("gフラグを使用しない1つの文字列を置換結果: "+resB);

実行結果

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
> true
> "gフラグを使用して一致文字列をすべて置換: 東京"
> "gフラグを使用しない1つの文字列を置換結果: 東京toto"
> true > "gフラグを使用して一致文字列をすべて置換: 東京" > "gフラグを使用しない1つの文字列を置換結果: 東京toto"
> true
> "gフラグを使用して一致文字列をすべて置換: 東京"
> "gフラグを使用しない1つの文字列を置換結果: 東京toto"

 

JavaScript

Posted by arkgame