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

Community
  • 1
  • 1
Codier
  • 2,126
  • 3
  • 22
  • 33

1 Answers1

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
  • 486
  • 3
  • 11
dev4life
  • 1,150
  • 10
  • 13
  • 3
    This is a bad string formatter implementation, as it can break if interpolated values resemble format strings. – Eric Sep 25 '13 at 20:55