6

I have a string that looks like this:

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

I'm curious of a good way to to detect the presence of {{ ... }} and replace the contents with the minLength variable. As you can probably expect there are a number of different variables like minLength, maxLength, etc. I've tried regex but can't seem to get it to work.

Fluidbyte
  • 5,162
  • 9
  • 47
  • 76

3 Answers3

10
var values = {
    minLength: 3
};

var text = "This field must be {{minLength}} characters";
var mystring = text.replace(/\{\{([^}]+)\}\}/, function(i, match) {
    return values[match];
});

demo

This way you can add more than one value to be replaced, you just have to add it do values and add g to the regex.

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

demo

Ricardo Alvaro Lohmann
  • 26,031
  • 7
  • 82
  • 82
  • You might return a default value, e.g. the expression or the empty string. Btw, it's `function(wholematch, firstgroup, index)…` – Bergi Dec 19 '12 at 17:51
5
var newString =  mystring.replace(/{{minLength}}/,minLength);
Matanya
  • 6,233
  • 9
  • 47
  • 80
1

You may use this approach:

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

Demo: fiddle

felipeclopes
  • 4,010
  • 2
  • 25
  • 35