In my attempt to create a simple template test, I encountered an issue with regular expressions. Despite using the \g
modifier, only the last occurrence is being replaced instead of all copies.
(How to String.match() distinct it ${SOME_TEXT} using Regex)
My goal is to prompt the user once for each unique variable name.
Title = t
name = n
result = '${Title} - n - t'
The pattern /\$\{([^\}]+)\}/g
works but results in multiple prompts for the user.
Title = t
name = n
Title = t
result = 't - n - t'
Is there a way to replace each token with a single value regardless of how many times it appears?
<html>
<head>
<script type="application/javascript">
window.copyToClipboard = function(n) {
var u = "_hiddenCopyText_", t, i, r;
t = document.getElementById(u);
t.textContent = n;
i = document.activeElement;
t.focus();
t.setSelectionRange(0, t.value.length);
try {
r = document.execCommand("copy")
} catch (f) {
r = !1
}
return i && typeof i.focus == "function" && i.focus(),
t.textContent = "",
r
};
//${varname}
window.templateRegex = /\$\{([^\}]+)\}(?![\S\s]*\$\{\1\})/g;
window.test = " ${Title} - ${Name} - ${Title}"
window.copyTemplate = function (template) {
var result = template.replace(window.templateRegex, function(match, token){
return window.prompt("replace value for ${"+token+"}","${"+token+"}");
});
window.copyToClipboard(result);
};
</script>
</head>
<textarea id="_hiddenCopyText_"></textarea>
<button onclick="copyTemplate(window.test)">Test</button>
</html>
JsFiddle https://jsfiddle.net/ksu37c3b/