Fast Javascript String Replacement

Hey geniuses SO!

This is for an autocomplete plugin that should receive data as an array of arrays and convert it using a format string (or regular expression). The format string can be any format.

var dataArray = [ ["data1-1", "data1-2", "data1-3"], ["data2-1", "data2-2", "data2-3"],... ];
var format = "<li>{0} <br /> -- <small> {1}, {2}</small></li>";
// alternate formats could be: 
//  "<li>{0}</li>"
//  "<a href="{0}" title="{2}">{1} ({2})</a>"
// etc...

function fillAutocomplete(datum,format){
    // do some magic here...
    // return "<li>data1-1 <br /> -- <small> data1-2, data1-3</small></li>";
}

The following idea works ... but I would like to know if something will be faster ...

var datum = data[0],
    html="<li>\{0\} <br /> -- <small> \{1\}, \{2\}</small></li>";
for(var i=0,l=datum.length;i<l;++i){
    var reg = new RegExp("\\{"+i+"\\}");
    html=html.replace(reg,datum[i]);
}

I am open to new ideas on how to approach this problem.

+3
source share
5 answers

Discard John Resig's β€œSearch and Don't Replace ” to see that you can pass a callback function myString.replace(..).

var datum = data[0];
var html="<li>{0}<br /> -- <small>{1}, {2}</small></li>";
var pattern = /\{(\d+)\}/g;

html = html.replace(pattern,function(match, key, value){
    return datum[key];
});
+11
source

, :

html = "<li>" + datum[0] 
        + " <br /> -- <small> " 
        + datum[1] + ", " + datum[2] 
        + "</small></li>";

for, . , , , - , .

, .

+1

. :

function fillAutocomplete(datum,format){
  return format.replace(/{([0-9]+)}/g, function(match) {
    return datum[match[1]];
  });
}
0

var datum = data[0],
    html="<li>{0} <br /> -- <small> {1}, {2}</small></li>";
for(var i=0,l=datum.length;i<l;++i){
    html=html.split("{" + i + "}").join(datum[i]);
}

, {n} .

0

, HTML:

html = [
  "<li>", datum[0],
  "<br /> -- <small>",
  datum[1], ", ", datum[2],
  "</small></li>"
].join("");

, DOM.

html = document.createElement("li");
html.appendChild(document.createTextNode(datum[0]));
html.appendChild(document.createElement("br"));
html.appendChild(document.createTextNode(" -- "));
html.appendChild(document.createElement("small"))
  .appendChild(document.createTextNode(datum[1] + ", " + datum[2]));
0
source

Source: https://habr.com/ru/post/1723171/


All Articles