有没有更简洁的方法来获取我网址中的最后一个数字?

时间:2018-07-13 11:56:51

标签: javascript

因此,我目前将两个变量传递到url中,以便在另一页上使用。我得到与location.hash的最后一个变量(即#12345)。然后从URL的另一部分(john%20jacob%202),我需要的只是'2'。我已经开始工作了,但是觉得必须有一种更简洁的方法来解决这个问题。 (john%20jacob%202)将始终更改为具有不同的字符串长度。

url: http://localhost/index.html?john%20jacob%202?#12345

<script>
    var hashUrl = location.hash.replace("?","");

       // function here to use this data

    var fullUrl = window.location.href;
    var urlSplit = fullUrl.split('?');
    var justName = urlSplit[1];
    var nameSplit = justName.split('%20');
    var justNumber = nameSplit[2];

       // function here to use this data

</script>

3 个答案:

答案 0 :(得分:1)

一个非常快的单线可能是这样的:

let url = 'http://localhost/index.html?john%20jacob%202?#12345';

url.split('?')[1].split('').pop();

// returns '2' 

答案 1 :(得分:1)

类似的东西

decodeURI(window.location.search).replace(/\D/g, '')

由于您的window.location.search是URI编码的,因此我们先对其进行解码。然后用数字代替所有不是数字的东西。对于您的特定URL,它将返回2


为清楚起见

您的示例位置http://localhost/index.html?john%20jacob%202?#12345由几部分组成,但是这里有趣的是?之后#之前的部分。

在Javascript中,可以通过search使用查询字符串(或window.location.search)这一有趣的部分。对于您的特定位置,window.location.search将返回?john%20jacob%202?

%20是URI编码的空间。为了对所有URI编码进行解码(即删除),我首先通过encodeURI函数运行search字符串。然后,使用正则表达式用空字符串替换该字符串中非数字的所有内容。

正则表达式/\D/匹配任何不是数字的字符,而g是一个修饰符,它指定我要匹配所有内容(不仅仅是在第一次匹配后停止),结果是{ {1}}。

答案 2 :(得分:0)

如果您知道自己一直在标签后面,则可以替换所有内容,直到“#”为止

url.replace(/^.+#/, '');

或者,此正则表达式将匹配您网址中的最后一个数字:

url.match(/(?<=\D)\d+$/);

//(positive look behind for any non-digit) one more digits until the end of the string
相关问题