2011-12-12 59 views
0

我有以下URL。从URL中查找子字符串

http://www.xyz.com/#tabname-1-12 

我需要从这个URL拆分3个值:

  • tabName:#的价值,但不希望-1-12)
  • 1:第一个值后,第一个 “ - ”
  • 12:第二个值之后第二个 “ - ”

我怎样才能做到这一点?

+1

什么ü迄今所做? – diEcho

+2

'需要拆分'在JavaScript中有一个叫'split'的函数(https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/split)。猜猜这是什么;) – Roman

回答

2

我会建议使用正则表达式和分裂。

HTML:

<div id='url'>http://www.xyz.com/#tabname-1-12</div> 

的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. 


}); 

使用var tabname = url.match(/#(.+?)-/);如果你不想在TABNAME前面的#。

工作例如: http://jsfiddle.net/QPxZX/

2

试试下面的正则表达式

#(.*)-(.*)-(.*) 

DEMO

0

也许它可以帮助你。用#分割你的网址,然后拿第二部分,然后用' - '分割,这样你就可以得到一个像val = {'tabname','1,''12'}这样的数组。试试吧,也许更好的答案等着你。

0

只需要将字符串拆分两次,然后就可以访问最终数组中的值。

var input = "http://www.xyz.com/#tabname-1-12"; 
var after = input.split('#')[1] 
var values = after.split('-'); 
document.write(values); 

http://jsfiddle.net/infernalbadger/E2q8q/

0

在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); 
0

简单的方法是,

<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> 
+0

这只适用于这个确切的URL,和一个名为tabname的选项卡。我怀疑这是他们想要的。 –