javascript 从 URL 中查找子字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8472091/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
find substring from a URL
提问by Lokesh Yadav
I have the following URL.
我有以下网址。
http://www.xyz.com/#tabname-1-12
I need to split 3 values from this URL:
我需要从此 URL 拆分 3 个值:
tabName
: the # value but do not want -1-12)1
: the first value after first "-"12
: second value after second "-"
tabName
: # 值但不想要 -1-12)1
: 第一个“-”之后的第一个值12
: 第二个“-”之后的第二个值
How can I do this?
我怎样才能做到这一点?
回答by thecodeassassin
I would recommend using a regex and a split.
我建议使用正则表达式和拆分。
HTML:
HTML:
<div id='url'>http://www.xyz.com/#tabname-1-12</div>
Javascript:
Javascript:
$(function() {
// set this to the element containing the actual URL
var url = $('#url').html();
// get tabname
var tabname = url.match(/(#.+?)-/);
tabname = tabname[1];
// you can now use the var tabname, which contains #tabname
var ids = url.split('-');
var idone = ids[1];
var idtwo = ids[2];
// idone contains 1, idtwo contains 12.
});
Use var tabname = url.match(/#(.+?)-/);
if you dont want the # in front of tabname.
var tabname = url.match(/#(.+?)-/);
如果您不想在选项卡名称前面使用#,请使用。
Working example: http://jsfiddle.net/QPxZX/
工作示例:http: //jsfiddle.net/QPxZX/
回答by maxRoald
in javascript:
在 JavaScript 中:
var url = 'http://www.xyz.com/#tabname-1-12';
// get values behind last slash
var threeValues = url.substring(url.lastIndexOf('/')).split('-');
var one = threeValues(0).substr(1); // get tabname
var two = threeValues(1);
var three = threeValues(2);
回答by Vid
The simple way is,
简单的方法是,
<html>
<body>
<script type="text/javascript">
var str = "http://www.xyz.com/#tabname-1-12";
var val1 = str.substr(20,7);
var val2 = str.substr(28,1);
var val3 = str.substr(31,2);
function displayVal()
{
alert("val1 = "+val1+"\nval2 = "+val2+"\nval3 = "+val3);
}
</script>
URL: http://www.xyz.com/#tabname-1-12;
<input type="button" name="btn" value="Click" onclick="displayVal()" />
</body>
</html>
回答by Pritom
Maybe it helps you. split your url with # and take 2nd part and then split with '-' and thus you would get a array like val={'tabname', '1,' '12'}. Just try it, maybe better answers waiting for you.
也许它可以帮助你。用 # 分割你的 url 并取第二部分,然后用 '-' 分割,因此你会得到一个像 val={'tabname', '1,' '12'} 这样的数组。试试吧,也许会有更好的答案等着你。
回答by Richard Dalton
Just need to split the string twice and then you can access the values from the final array.
只需要将字符串拆分两次,然后您就可以访问最终数组中的值。
var input = "http://www.xyz.com/#tabname-1-12";
var after = input.split('#')[1]
var values = after.split('-');
document.write(values);