5

我有一个看起来像这样的字符串:

var minLength = 3;
var mystring = "This field must be {{minLength}} characters"

我很好奇检测{{...存在}}并用 minLength 变量替换内容的好方法。正如您可能期望的那样,有许多不同的变量,例如 minLength、maxLength 等。我尝试了正则表达式,但似乎无法让它工作。

4

3 回答 3

9
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

演示

于 2012-12-19T17:44:44.817 回答
4
var newString =  mystring.replace(/{{minLength}}/,minLength);
于 2012-12-19T17:44:20.553 回答
0

您可以使用这种方法:

var str = "This field must be {{minLength}} characters";
var result = str.replace(/{{minLength}}/,"3");​​
alert(result);

演示:小提琴

于 2012-12-19T17:46:45.787 回答