JavaScript String Stitching Tips

Source: Internet
Author: User

String problems are often encountered in JavaScript, but it can be cumbersome to stitch strings too long.

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

Here are some tips on how to stitch strings in JavaScript.

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> ';
Stitching strings with arrays

Using the Join method of the 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.

Use the backslash ' to replace the original single or double quotation marks.

$ ('. Warning '). html ('    

Line breaks, indents, and spaces in a string are exported as-is to the newly generated string.

If you want to understand the performance of string stitching, it is recommended to look at Nicholas C.zakas's "high-performance JavaScript" book

JavaScript String Stitching Tips

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.