I have an input field that saves a URL, I’d like this saved input to recognize when “Http//” is absent from the start of the variable but have no idea where to begin… is it possible to check only a portion of a string? – then have a function that will append if necessary?
I have an input field that saves a URL, I’d like this saved input
Share
A simple solution for what you want is the following:
However there are a few things you should be aware of…
The test here is case-sensitive. This means that if the string is initially
Http://example.comthis will change it tohttp://Http://example.comwhich is probably not what you want. You probably should also not modify any string starting withfoo://otherwise you could end up with something likehttp://https://example.com.On the other hand if you receive an input such as
example.com?redirect=http://othersite.comthen you probably do want to prependhttp://so just searching for://might not be good enough for a general solution.Alternative approaches
Using a regular expression:
Using a URI parsing library such as JS-URI.
Related questions