在前端Javascript代码中,我需要从位置哈希参数中提取一个值。例如,url看起来像:
https://mywebsite.com/certainpage#comment-12345
在这里,我想提取值12345
,它表示注释的id。目前,我正在使用以下代码来完成它:
const match = window.location.hash.match(/-([0-9]*)/) || [];
if (!match[1]) return;
// Use match[1]
如果有任何优化和干净的方法来处理这个问题,请告诉我。
如果它总是#comment-NUM
,那么您甚至不需要使用RegEx。
const match = window.location.hash.split("-") || [];
然后同样的检查将适用。继续使用match[1]
。原因是String.split
在性能上优于String.match
。而且,它看起来也干净多了。