我正在尝试使用RegEx从URL中获取特定的单词。我已将单词作为数组包含在内,但似乎无法匹配或过滤数组中的任何单词。我总是收到一个错误,说'filter‘不是一个函数,尽管我看起来和别人以前用的差不多。
function replaceInput() {
var leadUrl = document.URL;
var utm_sources = [/linkedin/, /smartbrief/, /email_paid/, /paid_social/];
var get_source = leadUrl.filter(value => utm_sources.test(value));
var setUtm = get_source;
document.getElementById("LeadSourceTitle").placeholder = setUtm;
}
<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>
理想情况下,我要做的是检查这些单词是否存在,然后用相应的值向表单输入中添加一个值。
谢谢
发布于 2020-11-12 12:10:50
如果我没看错你的代码,你要找的是url的路径,而不是url本身。路径可以在location.pathname
中找到。如果没有匹配,则使用RegExp.match
传递null;如果找到匹配,则使用数组(如有必要进行过滤)。
所以,做一些类似以下的事情:
const re = /\/linkedin\/|\/smartbrief\/|\/email_paid\/|\/paid_social\//i;
const path = location.pathname.match(re);
const pathFaked1 = "/linkedin/?foo=bar&email_paid=1".match(re);
const pathFaked2 = "/email_paid/nope/shouldpaynow".match(re);
console.log(path);
console.log(pathFaked1.join(", "));
console.log(pathFaked2.join(", "));
https://stackoverflow.com/questions/64803253
复制相似问题