javascript - 您可以使用 RegEx 数组匹配 url 中的单词吗?
问题描述
我正在尝试使用 RegEx 从 URL 中获取特定单词。我已将单词作为数组包含在内,但我似乎无法匹配或过滤数组中的任何单词。我总是得到一个错误,“过滤器”不是一个函数,尽管我似乎使用它和其他人以前使用的一样。
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>
理想情况下,我想做的是检查这些词是否存在,然后将一个值添加到具有相应值的表单输入中。
谢谢
解决方案
如果我正确阅读了您的代码,那么您正在寻找 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(", "));
推荐阅读
- jenkins - Jenkins - 将变量写入日志文件
- java - Selenium ChromeDriver getPageSource() 不在无头模式下工作
- excel - 复杂的索引/匹配?还是 VLOOKUP?
- php - php - for 循环重复自身/乱序
- javascript - 有没有一种方法可以将 doc 值复制到另一个而不提取数据并发送回
- oauth-2.0 - keycloak 使用 oauth2 连接后端系统
- python - anti_captcha 无法再解决由 Selenium 控制的 Firefox/Chrome 上的 reCaptcha
- java - Map.Entry.comparingByValue().reversed() 的类型是什么?
- apache-spark - 由于 DeadlineExceededException,Spark 作业无法写入 Alluxio
- sql - 如何进行 SQL 查询,如果没有记录则返回 null,如果有则返回值?