Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript replace contents in string if exists

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.

like image 924
Fluidbyte Avatar asked Dec 19 '12 17:12

Fluidbyte


People also ask

What is replace () in JavaScript?

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.

How do you replace a substring in a string?

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).

How do you find and replace a character in a string in JavaScript?

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.


3 Answers

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

like image 65
Ricardo Alvaro Lohmann Avatar answered Nov 07 '22 23:11

Ricardo Alvaro Lohmann


var newString =  mystring.replace(/{{minLength}}/,minLength);
like image 32
Matanya Avatar answered Nov 07 '22 23:11

Matanya


You may use this approach:

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

Demo: fiddle

like image 34
felipeclopes Avatar answered Nov 07 '22 22:11

felipeclopes