Biorąc pod uwagę tę funkcję:JavaScript zastąpić/regex
function Repeater(template) {
var repeater = {
markup: template,
replace: function(pattern, value) {
this.markup = this.markup.replace(pattern, value);
}
};
return repeater;
};
Jak zrobić this.markup.replace()
zastąpić globalnie? Oto problem. Jeśli używam go w ten sposób:
alert(new Repeater("$TEST_ONE $TEST_ONE").replace("$TEST_ONE", "foobar").markup);
Wartość alertu to "foobar $ TEST_ONE".
Jeśli zmienię Repeater
do dalszej, nic w zastąpiony w Chrome:
function Repeater(template) {
var repeater = {
markup: template,
replace: function(pattern, value) {
this.markup = this.markup.replace(new RegExp(pattern, "gm"), value);
}
};
return repeater;
};
... a wpisowi $TEST_ONE $TEST_ONE
.
Ale replace() odbiera regex jako zmienną. – core
Drobna korekcja - '$' oznacza koniec wiersza w wyrażeniu regularnym. – harto
@Chris - Nie sądzę, żeby to miało znaczenie, jeśli użyjesz '/ pattern /' lub 'new RegExp (" pattern ")'. – harto