Forum Moderators: open
<script type="text/javascript">
function stringSubstitute(theText, param1, param2){
var newText = theText;
newText = newText.replace("{0}", param1);
newText = newText.replace("{1}", param2);
document.write(newText);
}stringSubstitute("Hi {0}. I am {1}.", "John","Sam");
</script>
[edited by: Trace at 1:45 pm (utc) on Oct. 23, 2007]
/**
* Substitute placeholders with string values
* @param {String} str The string containing the placeholders
* @param {Array} arr The array of values to substitute
*/
function substitute(str, arr)
{
var i, pattern, re, n = arr.length;
for (i = 0; i < n; i++) {
pattern = "\\{" + i + "\\}";
re = new RegExp(pattern, "g");
str = str.replace(re, arr[i]);
}
return str;
}
alert(substitute("The {0} has {1}", ["eagle", "landed"]));
alert(substitute("{0} ... {1} ... {0}", ["A", "B"]));