Here’s another answer with another approach.
You can use the .match() with a regular expression (Regex) to check what you need.
Test like this: addressBarValue.match(/https?:\/\//)
if (addressBarValue.match(/https?:\/\//)) {
frameSrc = addressBarValue;
} else {
frameSrc = "http://" + addressBarValue;
}
The expression searches both http and https and works like this:
http
- the exact string 'http'
s?
- optional, may or may not exist
:
- corresponds to :
literally
\/
- corresponds to bar /
but needs to be escaped with \
(2 times)
In relation to its variable frameSRC
, you are saving a string in the variable, not pointing to the element in order to rewrite its value. Use this way:
var frameSrc = document.getElementById('Frame'); // tirando o '.src'
and later on if/else
use frameSrc.src = addressBarValue;
, or changing the variable name to frame.src = etc...
The final code could be:
function goToWebsite() {
var addressBarValue = document.getElementById('AddressBar').value;
var frame = document.getElementById('Frame');
if (addressBarValue.match(/https?:\/\//)) {
frame.src = addressBarValue;
} else {
frame.src = "http://" + addressBarValue;
}
}
Doesn’t it work means that q always falls on Else? could give an example of the value of
addressBarValue
– rray
Just nothing happens even using the methods @bfavaretto taught, shows no error on the console, does not fall into Else, does not change Frame’s "src"...
– José Neto
An option would be with regex:
if (addressBarValue.match(/^https?:\/\//)) { ... } else { ... }
– user622
Same thing, browser shows no error on console, does not fall on Else, etc...
– José Neto
I excluded my answer because I was wrong, what I said was wrong. In fact, the code you have should work... unless there are spaces or other contents before http...'.
– bfavaretto