Possible Duplicate:
When is it better to use String.Format vs string concatenation?
Hi, I am writing String Interpolation for an open source Javascript library. I just get to know the concept of String interpolation and am a bit confused? Why do we even go into so much trouble to make String Interpolation? What are its advantages?
Also it there any resources on String interpolation in Javascript that you can point me to? Share with me?
Thanks
-
Why do we go into so much trouble to make tables?user395760– user3957602011年05月22日 14:02:25 +00:00Commented May 22, 2011 at 14:02
-
Uhhh it's easy to construct strings from variables that way...Rafe Kettler– Rafe Kettler2011年05月22日 14:02:26 +00:00Commented May 22, 2011 at 14:02
-
Resource: stackoverflow.com/questions/1408289/… diveintojavascript.com/projects/javascript-sprintfmplungjan– mplungjan2011年05月22日 14:19:41 +00:00Commented May 22, 2011 at 14:19
1 Answer 1
String interpolation is also known as string formatting. Advantages are:
1. code clarity
"<li>" + "Hello " + name + ". You are visitor number" + visitor_num + "</li>";
is harder to read and edit than
Java/.Net way
String.Format("<li> Hello {0}. You are visitor number {1}. </li>", name, visitor_num);
python way
"<li> Hello %s. You are visitor number %s</li>" % (name, visitor_num)
JavaScript popular way
["<li>","Hello",name,". You are visitor number",visitor_num,"</li>"].join(' ')
2. speed/memory use
Creating multiple strings and then concatenating them uses more memory and is slower than creating a single string one time.
I once wrote a javascript string formatter-
// simple string builder- usage: stringFormat("Hello {0}","world");
// returns "Hello world"
function stringFormat() {
var s = arguments[0];
for (var i = 0; i < arguments.length - 1; i++) {
var reg = new RegExp("\\{" + i + "\\}", "gm");
s = s.replace(reg, arguments[i + 1]);
}
return s;
}