Function with if and substring is not working

3

I am trying to create a function that when executed checks whether the substring of the value of a <input> is equal to link or link , but it is not working.

Is there something wrong with the code?

function goToWebsite() {
    var addressBarValue = document.getElementById('AddressBar').value;
    var frameSrc = document.getElementById('Frame').src;

    if ((addressBarValue.substring(0, 7) == "http://") || (addressBarValue.substring(0, 8) == "https://")) {
        frameSrc = addressBarValue;
    } else {
        frameSrc = "http://" + addressBarValue;
    }
}
    
asked by anonymous 14.06.2014 / 23:22

1 answer

2

Here's another answer with another approach.

You can use .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 looks for both http and https and works like this:

http - the exact string 'http'
s? - optional, may exist or not : - matches : literally \/ - matches bar / but needs to be escaped with \ (2 times)

For your variable frameSRC , you are saving a string to the variable, not pointing it to the element so you can rewrite its value. Use this:

var frameSrc = document.getElementById('Frame'); // tirando o '.src'

and later in% with% use if/else , or changing variable name to frameSrc.src = addressBarValue;

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;
    }
}
    
15.06.2014 / 00:34