我有一个看起来像这样的字符串:
var minLength = 3;
var mystring = "This field must be {{minLength}} characters"
我很想知道检测{{
... }}
是否存在的好方法,并用minLength变量替换内容。你可能会想到有很多不同的变量,比如minLength,maxLength等。我试过regex但似乎无法让它工作。
答案 0 :(得分:7)
var values = {
minLength: 3
};
var text = "This field must be {{minLength}} characters";
var mystring = text.replace(/\{\{([^}]+)\}\}/, function(i, match) {
return values[match];
});
通过这种方式,您可以添加多个要替换的值,只需添加values
并将g
添加到正则表达式。
var values = {
minLength: 3,
maxLength: 10
};
var text = "This field must be min {{minLength}} characters and max {{maxLength}}";
var mystring = text.replace(/\{\{([^}]+)\}\}/g, function(i, match) {
return values[match];
});
console.log(mystring); // This field must be min 3 characters and max 10
答案 1 :(得分:4)
var newString = mystring.replace(/{{minLength}}/,minLength);
答案 2 :(得分:0)
您可以使用此方法:
var str = "This field must be {{minLength}} characters";
var result = str.replace(/{{minLength}}/,"3");
alert(result);
演示:fiddle