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 = "pic_bulboff.gif";
} else {
image.src = "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 = "pic_bulboff.gif";
} else {
image.src = "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 :)
.match()
tests to see if a given string matches a regular expression.
In your example, it tests if image.src
contains the string "bulbon"
.
If there is a match, it changes image.src
to "pic_bulboff.gif"
For more information on this function, I recommend:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/match
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With