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

A brief discussion on JavaScript string splicing_javascript skills

WBOY
WBOYOriginal
2016-05-16 15:52:501420browse

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 = ['c93fdddc96bd78ea0e3ef30e92d4f8e9', '45a2772a6b6107b401db3c9b82c049c2Hello world54bdf357c58b8a65c66d7c19c8e4d114','bed06894275b65c1ab86501b08a632eb'].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