Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 427
user2994762 Avatar asked Jul 29 '14 18:07

user2994762


2 Answers

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 :)

like image 194
Mauno Vähä Avatar answered Oct 08 '22 18:10

Mauno Vähä


.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

like image 7
Jan Drewniak Avatar answered Oct 08 '22 19:10

Jan Drewniak