开发者

Why use String interpolation? [duplicate]

This question already has answers here: 开发者_如何学Go Closed 11 years ago.

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


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;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜