JavaScript查找匹配查询中的子字符串与对象

时间:2014-04-07 13:25:34

标签: javascript url object substring match

我想根据网址中出现的某些值在网页上显示一条消息。我有一个我正在寻找的已知字符串列表和相应的消息。我似乎无法通过查找/消息传递到任何地方。有人可以帮忙吗? JavaScript只是首选,而不是jquery。这不是我在这一点上的区别;)

非常感谢!

<div id="messagediv"></div>

要测试的示例网址:

<p><a href="#?utm_campaign=SpaComp123">Campaign 1</a>
<p><a href="#?utm_campaign=PoolComp123">Campaign 2</a>
<p><a href="#?utm_campaign=BeachComp123">Campaign 3</a>

<script>
(function () {
    var params = window.location.search.substring(1).split('&'),
    urlParams = {},
    key, val;
    for (var i = 01; i < params.length; i++) {
        urlParams[params.split('=')[0]] = params.split('=')[1];
    }

  // querystring is ?utm_campaign=SpaCamp12458
  // for instance, match URL query value SpaCamp12458 with the nums SpaComp key and show the corresponding text in the messagediv

  var nums = {
        defaultMessage: "Default Message",
        "SpaComp": "Spas",
        "PoolComp": "Recreation",
        "BeachComp": "Outdoors"
    }

    for (var i in nums) {
        if (nums.hasOwnProperty(i)) {
            var found = false;

            for (var j in urlParams) {
                if (urlParams.hasOwnProperty(j)) {
                    if (urlParams[j].indexOf(nums[i]) === 0) {
                        document.getElementById("messagediv").innerHTML = nums[i];
                        found = true;
                        break;
                    }
                }
            }

            if (!found) {
                document.getElementById("messagediv").innerHTML = nums.defaultMessage;
            }
        }
    }

})();

</script>

0 个答案:

没有答案