By using innerHTML, you're using markup. So one option is, just use markup (but more options follow):
var textDiv = document.createElement("div");
textDiv.innerHTML = data[i].text.replace(pattern, "<select></select>");
Live example:
var data = {
0: {
text: "This is a <strong>test</strong> {0} Testing <em>1 2 3</em>"
}
};
var i = 0;
var pattern = /\{0\}/i;
var textDiv = document.createElement("div");
textDiv.innerHTML = data[i].text.replace(pattern, "<select></select>");
document.body.appendChild(textDiv);
If you don't want to use markup, you can append the part of the string before the {0}, then the element, then the part of the string after the {0}:
var select = document.createElement("select"),
textDiv = document.createElement("div"),
text = data[i].text,
index = text.indexOf("{0}"); // No need for case-insensitivity
if (index === -1) {
index = text.length;
}
textDiv.innerHTML = text.substring(0, index);
textDiv.appendChild(select);
if (index < text.length) {
textDiv.insertAdjacentHTML("beforeend", text.substring(index + 3));
}
var data = {
0: {
text: "This is a <strong>test</strong> {0} Testing <em>1 2 3</em>"
}
};
var i = 0;
var select = document.createElement("select"),
textDiv = document.createElement("div"),
text = data[i].text,
index = text.indexOf("{0}"); // No need for case-insensitivity
if (index === -1) {
index = text.length;
}
textDiv.innerHTML = text.substring(0, index);
textDiv.appendChild(select);
if (index < text.length) {
textDiv.insertAdjacentHTML("beforeend", text.substring(index + 3));
}
document.body.appendChild(textDiv);
Or if the pattern has to be a regex:
var select = document.createElement("select"),
textDiv = document.createElement("div"),
text = data[i].text,
match = pattern.exec(text),
index = match ? match.index : text.length;
textDiv.innerHTML = text.substring(0, index);
textDiv.appendChild(select);
if (match) {
textDiv.insertAdjacentHTML("beforeend", text.substring(index + match[0].length));
}
var data = {
0: {
text: "This is a <strong>test</strong> {0} Testing <em>1 2 3</em>"
}
};
var i = 0;
var pattern = /\{0\}/i;
var select = document.createElement("select"),
textDiv = document.createElement("div"),
text = data[i].text,
match = pattern.exec(text),
index = match ? match.index : text.length;
textDiv.innerHTML = text.substring(0, index);
textDiv.appendChild(select);
if (match) {
textDiv.insertAdjacentHTML("beforeend", text.substring(index + match[0].length));
}
document.body.appendChild(textDiv);