Welcome to WebmasterWorld Guest from 54.197.116.116

Forum Moderators: open

Message Too Old, No Replies

javascript string substitution

   
7:27 am on Oct 23, 2007 (gmt 0)

5+ Year Member



I'm looking for something that does string substitution. Something like:

substitute("Hi {0}. I am {1}.", "John","Sam")

Which would result in:

Hi John. I am Sam.

I found a thread similar to this, but the solution there did not really help.

11:32 am on Oct 23, 2007 (gmt 0)

10+ Year Member



Hi,

there's no built-in function that will do this.

You'll have to build it yourself.

HTH,AA

1:23 pm on Oct 23, 2007 (gmt 0)

5+ Year Member




Try this;
<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]

3:34 pm on Oct 23, 2007 (gmt 0)

WebmasterWorld Senior Member fotiman is a WebmasterWorld Top Contributor of All Time 5+ Year Member Top Contributors Of The Month



Here's a solution I use:


/**
* 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"]));
6:29 am on Oct 24, 2007 (gmt 0)

5+ Year Member



Thanks Trace and Fotiman. That helps :)