How to parse web browser address using javascript and window.location?

I am unable to find the specific value in the address bar.

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

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

alert(x);

The code above does not return anything and actually kills anything (indicates an error), but nothing rushes to the console.

If you delete a comment, it works fine, returning a value greater than -1 (which means that it found something).

This is obviously something that I misunderstand, can someone help me?

+3
source share
4 answers

You should use window.location.hrefit because it window.locationis an object, not a string, and has a property searchthat contains the portion of the URL that follows? character including? symbol.

var str = window.location.href;

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

String.indexOf:

var str = window.location.href;

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

( ), , -1.

+6

window.location , . , var str = window.location.href?

+2

window.location - , search - , , - .

var str = window.location.toString();

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

.

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

window.location.path window.location.port .. window.location.hash .

-1

Source: https://habr.com/ru/post/1721210/


All Articles