homepage Welcome to WebmasterWorld Guest from 54.242.200.172
register, free tools, login, search, subscribe, help, library, announcements, recent posts, open posts,
Subscribe and Support WebmasterWorld
Home / Forums Index / Code, Content, and Presentation / JavaScript and AJAX
Forum Library, Charter, Moderator: open

JavaScript and AJAX Forum

    
javascript string substitution
xize




msg:3484763
 7:27 am on Oct 23, 2007 (gmt 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.

 

Arno_Adams




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

Hi,

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

You'll have to build it yourself.

HTH,AA

Trace




msg:3484976
 1:23 pm on Oct 23, 2007 (gmt 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]

Fotiman




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

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"]));

xize




msg:3485793
 6:29 am on Oct 24, 2007 (gmt 0)

Thanks Trace and Fotiman. That helps :)

Global Options:
 top home search open messages active posts  
 

Home / Forums Index / Code, Content, and Presentation / JavaScript and AJAX
rss feed

All trademarks and copyrights held by respective owners. Member comments are owned by the poster.
Terms of Service ¦ Privacy Policy ¦ Report Problem ¦ About
© Webmaster World 1996-2014 all rights reserved