Zubzob
Zubzob

Reputation: 2743

Knockout attr href output issue

I have a control that allows a user to save some links. He can add a display value of the link (basically the text within the <a>) and the link itself (the href attribute).

The problem is, I can't know whether he's adding the protocol as well (the http:// or https:// part, which is usually a result of copy-pasting a link from a browser's URL address bar) or he's manually typing 'www....'.

Basically, if the user types the address manually (www..) it will get appended to the current domain - here's an example - http://jsfiddle.net/ty4tLtkj/4/

This is avoided if the user appends the http:// part in front of the link - example here - http://jsfiddle.net/ty4tLtkj/5/

Is there a way to make sure the link that was entered NEVER gets appended to the domain name?

Upvotes: 0

Views: 60

Answers (2)

Roboroads
Roboroads

Reputation: 1709

Match the string for http;

var out = $("#input").val();
if(!out.match(/^https?:\/\//i)) //User didn't type http(s)://
{
    out = "http://" + out; //So add http://
}

Now: "http://google.nl" will be the same but "www.google.nl" will be "http://www.google.nl"

To explain .match(/^https?:\/\//i), this is regex:

  • ^ = begins with.
  • http
  • s? = s or no s.
  • :\/\/ = ://
  • i = case insensitive

Upvotes: 1

Tom Doodler
Tom Doodler

Reputation: 1559

Sure you can:

if (pathname.substring(0, 7) == "http://" || pathname.substring(0, 8) == "https://")

or

if (pathname.substring(0, 3) == "www")

Otherwise its not possible because links without http(s):// get automatically appended to the current url.

Upvotes: 1

Related Questions