【发布时间】:2020-11-12 17:48:50
【问题描述】:
我尴尬地花了 1.5 天的时间让下面的代码工作。使用 if else 语句感觉很笨拙,而且写得不好。我想知道是否有更好的方法来编写这个可以教会我更好地处理此类问题的方法。
代码的用途:
- 查找当前浏览器 URL 是什么(我在最后寻找营销参数,即 ?utm_source=linkedin&utm_medium=paid_social)
- 为特定参数设置 RegEx 查找
- 检查 URL 以查看它是否与这些参数中的任何一个匹配
- 记录结果
- 使用条件语句检查存在哪些参数组合(此时不要认为它甚至使用正则表达式)
- 相对于找到的组合设置表单输入值
欢迎任何建议!
function replaceInput() {
const leadUrl = window.location.href;
var utm_sources = RegExp(/linkedin|smartbrief|email_paid|paid_social/g);
var utms = leadUrl.match(utm_sources);
console.log(utms);
var leadSourceName = 'Other';
if (utms.includes('smartbrief')) {
console.log("We found Smartbrief");
leadSourceName = 'Smartbrief';
}
else if (utms.includes("linkedin" && "email_paid")) {
console.log("Linkedin Email");
leadSourceName = 'Linkedin Email';
}
else if (utms.includes("linkedin" && "paid_social")) {
console.log("Linkedin social");
leadSourceName = 'Linkedin Social';
}
else {
console.log("No UTMs found");
}
document.getElementById("LeadSourceTitle").value = leadSourceName;
}
html {
font-family: source_sans_proregular,-apple-system,blinkmacsystemfont,Segoe UI,Roboto,Oxygen,Ubuntu,Cantarell,Fira Sans,Droid Sans,Helvetica Neue,arial,helvetica,sans-serif;
color: #444;
}
input {
height: 51px;
width: 50%;
font-size: 1.25em;
border: 2px solid #c5c5c5;
caret-color: #44c0ff;
padding: 0 0 0 15px;
}
input:focus {
border: 2px solid #44c0ff;
outline: none;
}
<html>
<head>
<link rel="stylesheet" href="styles.css">
<script src="utm-url-test.js"></script>
</head>
<body>
<h1>Form test</h1>
<p>Populate the webform input with the utm of the url.</p>
<form>
<input id="LeadSourceTitle" placeholder="This should be replaced with UTM" onfocus="replaceInput()"></input>
</form>
</body>
</html>
【问题讨论】:
标签: javascript arrays regex if-statement