I’m trying to take the input string and verify whether an image exists on the URL.
When I click the ‘Check’ button, the intended result is to validate whether the input value is a regex match. If it is or is not, display an appropriate result.
JS
JavaScript
x
10
10
1
checkImage.addEventListener("click", function () {
2
let url = document.getElementById("inputUrl").value;
3
// console.log(url);
4
5
if (typeof url !== "string") result.textContent = "This is not an image";
6
return url.match(/.(jpg|jpeg|gif|png)$/) != null;
7
8
result.textContent;
9
});
10
JavaScript
1
9
1
checkImage.addEventListener("click", function () {
2
let url = document.getElementById("inputUrl").value;
3
// console.log(url);
4
5
if (typeof url !== "string") result.textContent = "This is not an image";
6
return url.match(/.(jpg|jpeg|gif|png)$/) != null;
7
8
result.textContent;
9
});
JavaScript
1
6
1
<form action="">
2
<input type="text" id="inputUrl" placeholder="url of image">
3
<button type="button" id="checkImage">Check</button>
4
</form>
5
6
<h3 id="result">?</h3>
Advertisement
Answer
You’re return
ing from the event handler before anything is put in the result div.
A few other notes.
- using
regex.test()
is the appropriate method for testing if a string matches a pattern. Thematch
method you used, although it will work, is intended for extracting parts of a string. - Your
url
variable will always be a string as the value of an input, so checking that is unnecessary.
JavaScript
1
8
1
var checkImage = document.getElementById("checkImage");
2
var result = document.getElementById("result");
3
4
checkImage.addEventListener("click", function () {
5
let url = document.getElementById("inputUrl").value;
6
var is_image = /.(jpg|jpeg|gif|png)$/.test(url);
7
result.textContent = is_image ? 'valid image' : 'invalid';
8
});
JavaScript
1
6
1
<form action="">
2
<input type="text" id="inputUrl" placeholder="url of image">
3
<button type="button" id="checkImage">Check</button>
4
</form>
5
6
<h3 id="result">?</h3>