I'm wondering if there is a cleaner way to write this javascript code. if
within if
seems pretty average. Happy to use es5/es6
if possible. Basically, I'm checking to see if a variable exists, if it does exist I want to make sure the url contains https
and update it if it doesn't.
if (blogURL) {
if (!/^https?:\/\//i.test(blogURL)) {
var blogURL = 'http://' + blogURL;
}
}
Use &&
to test both conditions in a single if
statement and remove the var as you presumably just want to update the existing variable, not look like you're trying to define a new variable.
if (blogURL && !/^https?:\/\//i.test(blogURL)) {
blogURL = 'http://' + blogURL;
}
This works because if the first conditional test fails, then the second conditional test is not executed. This is a common way to do something like this in Javascript.