2

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

asked May 22, 2011 at 14:01
3

1 Answer 1

13

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;
}
jdhartley
4863 silver badges11 bronze badges
answered May 22, 2011 at 14:31
Sign up to request clarification or add additional context in comments.

1 Comment

This is a bad string formatter implementation, as it can break if interpolated values resemble format strings.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.