Search code examples
javascriptuserscripts

How to replace text of current document URL using javascript


Ex:

Following is my current document.

http://www.youtube.com/watch?v=cgxJHBJ_X-g&feature=related

I have a User Script and the code is

var doc = document.location.toString();
doc = doc.replace("v=cgxJHBJ_X-g","v=2AGrlGvtLxE");

I am just trying to replace the current document URL with some other URL. But I am getting the following Error.

Uncaught TypeError: Object http://www.youtube.com/watch?v=cgxJHBJ_X-g&feature=related has no method 'replace'


Solution

  • Use document.URL or window.location.href instead of document.location.toString().

    Example:

    var url = document.URL;
    window.location.href = url.replace("v=cgxJHBJ_X-g","v=2AGrlGvtLxE").