JavaScript string stitching Tips (recommended) _javascript tips

Source: Internet
Author: User
Tags stringbuffer

The problem with strings is often encountered in JavaScript, but it is more cumbersome to have strings that are spliced too long.

If it is on a line, the readability is not said, if you want to change the line, will directly error.

Here are some tips for JavaScript stitching strings.

string addition (+)

var items = ' <li class= ' details ' > ' + ' 
      <span>hello world</span> ' + 
      ' </li> '; 

Stitching strings with backslashes

var items = ' <li class= ' details ' > ' 
      <span>hello world</span> ' 
      </li> '; 

Using Arrays to stitch strings

Using the Join method of an array, the array is converted to a string.

var emplist = [' <li class= ' details ' > ', ' <span>hello world</span> ', ' </li> '].join (""); 

On the basis of an array, a StringBuffer method can be encapsulated to complete the concatenation of strings.

function StringBuffer () { 
  this.buffer = []; 
} 
Stringbuffer.prototype = { 
  Constructor:stringbuffer, 
  append:function (str) { 
    this.buffer.push (str); 
    return this; 
  }, 
  tostring:function () {return 
    this.buffer.join ('); 
  } 
}; 

ES6 Template String

A new type of literal syntax, called a template string, is introduced in ES6.

Replace the original single or double quotation marks with the reverse apostrophe.

$ ('. Warning '). html (' 
   
 

The newline, indent, and whitespace in the string are exported to the newly generated string as-is.

If you want to understand the performance issues of string concatenation, it is recommended to see Nicholas C.zakas's "High Performance JavaScript" book

The above JavaScript string stitching tips (recommended) is small to share all the content of everyone, hope to give you a reference, but also hope that we support the cloud-dwelling community.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.