Home >Web Front-end >JS Tutorial >A brief discussion on JavaScript string splicing_javascript skills

A brief discussion on JavaScript string splicing_javascript skills

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOriginal
2016-05-16 15:52:501497browse

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>';

2. Use backslashes to concatenate strings

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

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());

    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.

    Statement:
    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