Function with if and substring is not working

Asked

Viewed 179 times

3

I am trying to create a function that will check if the substring of the value of a <input> is equal to http:// or https://, but it’s not working.

There’s 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;
    }
}
  • Doesn’t it work means that q always falls on Else? could give an example of the value of addressBarValue

  • 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"...

  • An option would be with regex: if (addressBarValue.match(/^https?:\/\//)) { ... } else { ... }

  • Same thing, browser shows no error on console, does not fall on Else, etc...

  • 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...'.

1 answer

2


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;
    }
}
  • The problem was with declaring the variable "frameSrc", tried it your way without declaring and it worked.

  • @Joséneto, therefore, edited my answer to explain this. I am glad that you have solved the problem.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.