I have embarrassingly spent 1.5 days getting the below piece of code to work. It feels clunky using if else statements and poorly written. I wonder if there is a better way to write this that might teach me a better way to handle this type of problem.
What the code is meant to do:
- Find what the current browser URL is (im looking for marketing parameters on the end i.e. ?utm_source=linkedin&utm_medium=paid_social)
- Set a RegEx look up for particular parameters
- Check the URL to see if it matches any of those parameters
- Log the result
- Use a conditional statement to check which combination of parameters exist (don't think it's even using regex at this point)
- Set the form input value relative to the combination found
Any advice welcomed!
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>
Aucun commentaire:
Enregistrer un commentaire