SoFunction
Updated on 2025-03-01

Simple example of JS patchwork strings

Like Java, it is very resource-consuming to use the "+" sign in JS to piece together strings, so in the case of a large number of strings, we also need a tool similar to StringBuffer.

The following uses the () method to implement StringBuffer

function StringBuffer() { 
  this._strs = new Array; 
} 
 = function (str) { 
  this._strs.push(str); 
}; 
 = function() { 
  return this._strs.join(""); 
};

use:

var sb=new StringBuffer();

("sss")

("ddd");

(); //"sssddd"

Attached the string formatting method used in a project

/**
 * Format string
 * format("{0},{1}","ddd","fff");
 * format('<button type="{1}">{2}</button>',"btnOk","Button","Ok")
 **/
function format(str){
  for(var i=0;i&lt;-1;i++){
    var placeHolder="{"+i+"}";
    if((placeHolder)!=-1){
      str=(placeHolder,arguments[i+1]);
    }
  }
  return str;
}

The above simple example of JS pieced together strings is all the content I share with you. I hope you can give you a reference and I hope you can support me more.