Welcome to WebmasterWorld Guest from 23.20.239.237

Forum Moderators: open

Message Too Old, No Replies

javascript string substitution

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

New User

5+ Year Member

joined:Oct 23, 2007
posts: 12
votes: 0


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)

Junior Member

10+ Year Member

joined:Dec 7, 2004
posts:130
votes: 0


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)

Preferred Member

10+ Year Member

joined:July 5, 2005
posts:352
votes: 0



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)

Senior Member from US 

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

joined:Oct 17, 2005
posts:4987
votes: 12


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)

New User

5+ Year Member

joined:Oct 23, 2007
posts: 12
votes: 0


Thanks Trace and Fotiman. That helps :)
 

Join The Conversation

Moderators and Top Contributors

Hot Threads This Week

Featured Threads

Free SEO Tools

Hire Expert Members