我试图做一个快速和脏的模板测试,但当正则表达式替换时,它只替换最后一次出现,我认为\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>
的jsfiddlehttps://jsfiddle.net/ksu37c3b/
提示3次,不是两次。 –
@Ryan The Leach我更新了我的答案,上面的代码提示2次。 –