Với chức năng này:JavaScript thay thế/regex
function Repeater(template) {
var repeater = {
markup: template,
replace: function(pattern, value) {
this.markup = this.markup.replace(pattern, value);
}
};
return repeater;
};
Làm thế nào để làm cho this.markup.replace()
thay thế trên toàn cầu? Đây là vấn đề. Nếu tôi sử dụng nó như thế này:
alert(new Repeater("$TEST_ONE $TEST_ONE").replace("$TEST_ONE", "foobar").markup);
Giá trị của cảnh báo là "foobar $ TEST_ONE".
Nếu tôi thay đổi Repeater
đến những điều sau đây, sau đó không có gì trong thay thế trong Chrome:
function Repeater(template) {
var repeater = {
markup: template,
replace: function(pattern, value) {
this.markup = this.markup.replace(new RegExp(pattern, "gm"), value);
}
};
return repeater;
};
... và cảnh báo là $TEST_ONE $TEST_ONE
.
Nhưng replace() nhận regex như là một biến. – core
Chỉnh sửa nhỏ - '$' biểu thị kết thúc của dòng trong một regexp. – harto
@Chris - Tôi không nghĩ rằng nó tạo ra sự khác biệt nếu bạn sử dụng '/ pattern /' hoặc 'new RegExp ("pattern") '. – harto