在JavaScript字符串中拆分最后一个字值

时间:2015-09-29 17:04:39

标签: javascript jquery asp.net .net

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

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

  1. 检查国家/地区是否存在上述网址,上面的网址中只有一个countryId

  2. 获取countryId值表示875567。

  3. 非常感谢大家对这种良好的反应。我得到了解决方案,大部分答案都是正确的。

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

6 个答案:

答案 0 :(得分:1)

使用

获取网址

window.location.href

并且

与'?'分开?首先,'&'下一步' ='这样你就可以获得countryId

OR

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

答案 1 :(得分:0)

这样的事情怎么样:

var TheString = "/MyProject/Information/EmpDetails.aspx?userId=79874&countryId=875567";

var TheCountry = parseInt(TheString.split('=').pop(), 10);

然后你只需要测试TheCountry是否为if (TheCountry) { ...}

这当然假设URL查询字符串最后总是有国家ID。

答案 2 :(得分:0)

您需要使用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
}

答案 3 :(得分:0)

var url ='/MyProject/Information/EmpDetails.aspx?userId=79874& countryId=875567';
alert((url.match(/countryId/g) || []).length);
alert(url.substring(url.lastIndexOf('=')+1));

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

答案 4 :(得分:0)

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

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的值以获取值

答案 5 :(得分:0)

您也可以拆分字符串并查看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());
}
相关问题