【问题标题】:Split last word value in JavaScript string [duplicate]拆分JavaScript字符串中的最后一个单词值[重复]
【发布时间】:2015-12-27 06:41:35
【问题描述】:

我在下面的 JavaScript 中有一个 URL 字符串 ex- 网址-"/MyProject/Information/EmpDetails.aspx?userId=79874&countryId=875567"

现在,我需要做以下两件事

  1. 检查上面的url中是否存在国家,上面的url中只有一个countryId

  2. 获取countryId值表示875567。

感谢大家这么快的回复。我得到了解决方案,大部分答案都是正确的。

还有一个问题,伙计们,我有超链接,所以我在 onmousedown 事件时会生成一些活动。但问题是即使我只右键单击它也会触发..但我想要仅在单击超链接双击或时触发的事件右键单击,然后单击

【问题讨论】:

    标签: javascript jquery asp.net .net


    【解决方案1】:

    获取网址使用

    window.location.href

    还有

    用 '?' 分割首先,'&' next 和 '=' 这样你就可以得到 countryId

    直接用 '=' 进行拆分,并从拆分后得到的数组中获取最后一个值

    【讨论】:

      【解决方案2】:

      这样的事情怎么样:

      var TheString = "/MyProject/Information/EmpDetails.aspx?userId=79874&countryId=875567";
      
      var TheCountry = parseInt(TheString.split('=').pop(), 10);
      

      然后您只需要测试TheCountry 是否与if (TheCountry) { ...} 匹配

      这当然假设 URL 查询字符串的末尾总是有国家 ID。

      【讨论】:

        【解决方案3】:

        您需要使用indexOf()substring() 的组合

        var ind = url.indexOf("countryId");
        if (ind  != -1){
            // value is index of countryid plus length (10)
            var countryId = url.substring(ind+10);
        }else{
            //no countryid
        }
        

        【讨论】:

          【解决方案4】:
          var url ='/MyProject/Information/EmpDetails.aspx?userId=79874& countryId=875567';
          alert((url.match(/countryId/g) || []).length);
          alert(url.substring(url.lastIndexOf('=')+1));
          

          您可以获取第一次警报中任何字符串的出现次数,并通过子字符串获取 countryid 值。

          【讨论】:

            【解决方案5】:

            这会将您的 url 查询转换为对象

            var data = url.split('?')[url.split('?').length - 1].split('&').reduce(function(prev, curr){
                var fieldName = curr.split('=')[0]; 
                var value = curr.split('=').length > 1 ? curr.split('=')[1] : '';
                prev[fieldName] = value; 
                return prev
            }, {});
            

            那么你可以只检查 data.country 的值来获取值

            【讨论】:

              【解决方案6】:

              你也可以拆分字符串,看看countryId是否存在,如下所示。

              var myString = "/MyProject/Information/EmpDetails.aspx?userId=79874&countryId=875567";
              myString = myString.split("countryId="); //["/MyProject/Information/EmpDetails.aspx?userId=79874&", "875567"]
              if (myString.length === 2) {
                  alert (myString.pop());
              }
              

              【讨论】:

                猜你喜欢
                • 2019-01-11
                • 2016-01-18
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 2019-11-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                相关资源
                最近更新 更多