Home > Web Front-end > JS Tutorial > body text

A brief discussion on JavaScript string splicing_javascript skills

WBOY
Release: 2016-05-16 15:52:50
Original
1384 people have browsed it

String concatenation is often encountered in JavaScript, but it is more troublesome if the string to be concatenated is too long.

If it is on one line, the readability is too poor; if it is changed to a new line, an error will be reported directly.

Now let’s introduce a few tips for splicing strings in JavaScript (mainly for situations where strings are too long).

1. String addition ( )

var empList = ' <li data-view-section="details">'+
      '<span>Hello world</span>'+
     '</li>';
Copy after login

2. Use backslashes to concatenate strings

var empList = ' <li data-view-section="details">\
      <span>Hello world</span>\
    </li>';
Copy after login

3. Use arrays to concatenate strings

Copy code The code is as follows:

var empList = ['
  • ', 'Hello world','
  • '].join("");

    Use the join method of the array to convert the array into a string

    function StringBuffer(){
      this.buffer = [];
    }
    //将新添加的字符串添加到数组中
    StringBuffer.prototype.append = function(str){
      this.buffer.push(str);
      return this;
    };
    //转成字符串
    StringBuffer.prototype.toString = function(){
      return this.buffer.join("");
    };
    //用法
    var buffer = new StringBuffer();
    buffer.append("hello");
    buffer.append(',world');
    console.log(buffer.toString());
    Copy after login

    Based on the array method, a class similar to StringBuffer in Java can be encapsulated to complete string splicing.

    The above is the entire content of this article, I hope you all like it.

    Related labels:
    source:php.cn
    Statement of this Website
    The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
    Popular Tutorials
    More>
    Latest Downloads
    More>
    Web Effects
    Website Source Code
    Website Materials
    Front End Template