string replace with placeholder javascript
var replacements = {
“%NAME%”: “Mike”,
“%AGE%”: “26″,
“%EVENT%”: “20″
},
str = ‘My Name is %NAME% and my age is %AGE%, the following %TOKEN% is invalid.’;
“%NAME%”: “Mike”,
“%AGE%”: “26″,
“%EVENT%”: “20″
},
str = ‘My Name is %NAME% and my age is %AGE%, the following %TOKEN% is invalid.’;
str = str.replace(/%\w+%/g, function(all) {
return replacements[all] || all;
});
return replacements[all] || all;
});
document.body.innerHTML = str;
Some more examples related to replace regular expression
var country = "india india INDIA .";
alert(country.replace('india', 'US'));
alert(country.replace(/india/g, 'US'));
alert(country.replace(/india/gi, 'US'));
alert(country.replace(/\./g, 'US'));