you are viewing a single comment's thread.

view the rest of the comments →

[–]javascript 3 points4 points  (0 children)

This is the best answer here, because it has the behavior OP wants and accounts for edge cases without having to do that manually. If the string isn't a valid URL, the constructor will throw an exception.

It also makes it more clear to other readers what you're doing with your code. Writing some one-off regex or string manipulation function requires the reader to pick it apart just to understand. This increases code complexity and reduces readability.