2

my code

let url = new URL('http://www.test.com/t.html?a=1&b=3&c=m2-m3-m4-m5');
let searchParams = new URLSearchParams(url.search);
console.log(searchParams.get('c'));  // outputs "m2-m3-m4-m5"

and the error

Uncaught TypeError: URL is not a constructor

2
  • 2
    What browser are you using? Have you checked here ~ developer.mozilla.org/en-US/docs/Web/API/… Commented Feb 6, 2019 at 4:03
  • I am using the latest version of chrome @Phill Commented Feb 6, 2019 at 4:42

2 Answers 2

9

The only thing that would cause this error in any recent version of Chrome (at least since 2014's v32) would be if you had some other code that overwrote the URL symbol.

For example

const URL = 'I am now a string'

// later...

let url = new URL('http://www.test.com/t.html?a=1&b=3&c=m2-m3-m4-m5');

If you're having trouble locating the code that's overwriting URL, you could start by simply adding

console.log(URL)

to your code. The value logged may give you a hint. Otherwise, see this post ~ How to know in which file that defined a js global var in chrome console?


Solutions:

  • Try not to use global object names in your variables.
  • Don't assign global variables if you can help it.

On that last note, you could avoid this problem like this

(function() {
  const URL = 'I am a string but not window.URL'

  // later...

  let url = new window.URL('http://www.test.com/t.html?a=1&b=3&c=m2-m3-m4-m5');
  console.info(url.search)
})()

Sign up to request clarification or add additional context in comments.

2 Comments

this code still gives me a error but it says window.URL is not a constructor
You must have some other code that is setting URL in the global / window scope. You should try and find it
0

The problem occurs because url.URL is undefined (read more in this comment).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.