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.
The replace() method returns a new string with one, some, or all matches of a pattern replaced by a replacement . The pattern can be a string or a RegExp , and the replacement can be a string or a function called for each match. If pattern is a string, only the first occurrence will be replaced.
Algorithm to Replace a substring in a stringInput the full string (s1). Input the substring from the full string (s2). Input the string to be replaced with the substring (s3). Find the substring from the full string and replace the new substring with the old substring (Find s2 from s1 and replace s1 by s3).
Answer: Use the JavaScript replace() method You can use the JavaScript replace() method to replace the occurrence of any character in a string. However, the replace() will only replace the first occurrence of the specified character. To replace all the occurrence you can use the global ( g ) modifier.
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
var newString = mystring.replace(/{{minLength}}/,minLength);
You may use this approach:
var str = "This field must be {{minLength}} characters";
var result = str.replace(/{{minLength}}/,"3");
alert(result);
Demo: fiddle
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With