最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How do I parse the web browser address using javascript and window.location? - Stack Overflow

programmeradmin3浏览0评论

I'm finding it impossible to search for a particular value within the Address Bar.

var str = window.location;
//var str = "/";

var x = str.search(/78203/i);

alert(x);

The above code returns nothing, and in fact kills the running of anything else (indicating an error) but nothing is thrown in the console.

If you remove the ment, it runs fine, returning a value of more than -1 (meaning it's found something).

This is obviously something I'm not understanding correctly, can someone help me out?

I'm finding it impossible to search for a particular value within the Address Bar.

var str = window.location;
//var str = "http://www.website./78203/";

var x = str.search(/78203/i);

alert(x);

The above code returns nothing, and in fact kills the running of anything else (indicating an error) but nothing is thrown in the console.

If you remove the ment, it runs fine, returning a value of more than -1 (meaning it's found something).

This is obviously something I'm not understanding correctly, can someone help me out?

Share Improve this question edited Oct 27, 2009 at 19:41 jakeisonline asked Oct 27, 2009 at 17:38 jakeisonlinejakeisonline 1,2061 gold badge11 silver badges24 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 6

You should use window.location.href, because window.location is an object, not a string, and it has a search property, which contains the part of the URL that follows the ? symbol, including the ? symbol.

var str = window.location.href;

var x = str.search(/78203/i);

You can also use the String.indexOf function:

var str = window.location.href;

var x = str.indexOf('78203');

They both will return you the character position of the first occurrence of the searched string (or pattern), and if the value is not found, it will return you -1.

window.location is actually a Location object, not a string. What happens if you replace your code with var str = window.location.href?

window.location is an object, and search is only a method of strings, so it needs to be converted to a string before you can do anything string-y with it.

var str = window.location.toString();

var x = str.search(/78203/i);

The browser already parses the location for you.

http://www.w3schools./jsref/obj_location.asp

You can access window.location.path or window.location.port, etc. You can even use window.location.hash to get the anchor.

发布评论

评论列表(0)

  1. 暂无评论