Как я могу сделать интерполяцию строк в JavaScript?

Нет необходимости хранить ответ в элементе, не используйте DOMParser ()

Просто установите responseType в «document», и ответ будет автоматически проанализирован и сохранен в responseXML

Пример:

var ajax = new XMLHttpRequest();
ajax.open('get','http://www.taringa.net');
ajax.responseType = 'document';
ajax.onload = function(){
    console.log(ajax.responseXML); //And this is a document which may execute getElementById
};
ajax.send();
441
задан thefourtheye 19 November 2015 в 23:52
поделиться

4 ответа

Пользовательская гибкая интерполяция:

var sourceElm = document.querySelector('input')

// interpolation callback
const onInterpolate = s => `<mark>${s}</mark>`

// listen to "input" event
sourceElm.addEventListener('input', parseInput) 

// parse on window load
parseInput() 

// input element parser
function parseInput(){
  var html = interpolate(sourceElm.value, undefined, onInterpolate)
  sourceElm.nextElementSibling.innerHTML = html;
}

// the actual interpolation 
function interpolate(str, interpolator = ["{{", "}}"], cb){
  // split by "start" pattern
  return str.split(interpolator[0]).map((s1, i) => {
    // first item can be safely ignored
	  if( i == 0 ) return s1;
    // for each splited part, split again by "end" pattern 
    const s2 = s1.split(interpolator[1]);

    // is there's no "closing" match to this part, rebuild it
    if( s1 == s2[0]) return interpolator[0] + s2[0]
    // if this split's result as multiple items' array, it means the first item is between the patterns
    if( s2.length > 1 ){
        s2[0] = s2[0] 
          ? cb(s2[0]) // replace the array item with whatever
          : interpolator.join('') // nothing was between the interpolation pattern
    }

    return s2.join('') // merge splited array (part2)
  }).join('') // merge everything 
}
input{ 
  padding:5px; 
  width: 100%; 
  box-sizing: border-box;
  margin-bottom: 20px;
}

*{
  font: 14px Arial;
  padding:5px;
}
<input value="Everything between {{}} is {{processed}}" />
<div></div>
0
ответ дан 22 November 2019 в 22:57
поделиться

Вы можете использовать систему шаблонов Prototype , если вам действительно хочется разбить орех кувалдой:

var template = new Template("I'm #{age} years old!");
alert(template.evaluate({age: 21}));
21
ответ дан 22 November 2019 в 22:57
поделиться

Попробуйте sprintf . Например:

vsprintf('The first 4 letters of the english alphabet are: %s, %s, %s and %s', ['a', 'b', 'c', 'd']);
23
ответ дан 22 November 2019 в 22:57
поделиться

Douglas Crockford's Remedial JavaScript includes a String.prototype.supplant function. It is short, familiar, and easy to use:

String.prototype.supplant = function (o) {
    return this.replace(/{([^{}]*)}/g,
        function (a, b) {
            var r = o[b];
            return typeof r === 'string' || typeof r === 'number' ? r : a;
        }
    );
};

// Usage:
alert("I'm {age} years old!".supplant({ age: 29 }));
alert("The {a} says {n}, {n}, {n}!".supplant({ a: 'cow', n: 'moo' }));

If you don't want to change String's prototype, you can always adapt it to be standalone, or place it into some other namespace, or whatever.

186
ответ дан 22 November 2019 в 22:57
поделиться
Другие вопросы по тегам:

Похожие вопросы: