Categories
html image javascript match toggle

Explain image.src.match in javascript

I was following this tutorial and I found some javascript code difficult to understand.

Link to tutorial

http://www.w3schools.com/js/tryit.asp?filename=tryjs_lightbulb

Code I need to clarify

<script>
function changeImage() {
var image = document.getElementById('myImage');
if (image.src.match("bulbon")) {
image.src = "https://www.faqcode4u.com/faq/414398/pic_bulboff.gif";
} else {
image.src = "https://www.faqcode4u.com/faq/414398/pic_bulbon.gif";
}
}
</script>

I do not understand what MATCH (in image.src.match) actually means.
Is it something that has a toggling action.
I could not find any useful article for this.

Well, @elclanrs already provided a link for the String.prototype.match() explanation. However, below is an answer which clarifies some things for you.

HTML:

<img id="myImage" src="http://www.w3schools.com/js/pic_bulbon.gif" />

JavaScript:

// capture the image
var image = document.getElementById('myImage');
console.log(image.src); // http://www.w3schools.com/js/pic_bulbon.gif
console.log(image.src.match("word-not-in-src-name")); // null
console.log(image.src.match("bulbon")); // ["bulbon", index: 32, input: "http://www.w3schools.com/js/pic_bulbon.gif"]
// image.src.match("bulbon") will return an Array, but it evaluates true in JavaScript
// This is the reason why "Evaluates true!" is printed out to console
if(image.src.match("bulbon")) {
console.log("Evaluates true!");
}
// To prove my point, "Empty array!" also will be printed out to console
if([]) {
console.log("Empty array!");
}

You can see this yourself from following JS FIDDLE EXAMPLE

Therefore, to get back in your code example:

if (image.src.match("bulbon")) {
image.src = "https://www.faqcode4u.com/faq/414398/pic_bulboff.gif";
} else {
image.src = "https://www.faqcode4u.com/faq/414398/pic_bulbon.gif";
}

..means that if bulbon word is in current image src attribute, image will be changed to be pic_bulboff.gif because execution will move inside the if block, because image.src.match("bulbon") will return an Array, (as demonstrated in my above example, and explained in the docs as well).

Cheers, hopefully you now understand how to check if some word is part of a string in the future 🙂