首页 > 解决方案 > 您可以使用 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>

理想情况下,我想做的是检查这些词是否存在,然后将一个值添加到具有相应值的表单输入中。

谢谢

标签: javascriptregex

解决方案


如果我正确阅读了您的代码,那么您正在寻找 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(", "));


推荐阅读