【发布时间】:2017-01-23 02:34:57
【问题描述】:
我正在尝试进行快速而肮脏的模板测试,但是当正则表达式替换时,它只替换最后一次出现,我认为\g 会替换所有副本。但它只匹配最后一次出现。
(How to String.match() distinct it ${SOME_TEXT} using Regex)
我要做的是提示用户输入每个唯一的变量名称。
Title = t
name = n
result = '${Title} - n - t'
使用/\$\{([^\}]+)\}/g 有效,但会多次提示用户。
Title = t
name = n
Title = t
result = 't - n - t'
那么,无论出现多少次,如何将每个标记替换为单个值。
<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/
【问题讨论】:
标签: javascript regex