Dennis Smit
Dennis Smit

Reputation: 19

Jquery loop ending when variable is empty?

My code makes a map from a video game which is built with a large amount of smaller images.

Now the problem is at the last loop it inserts an image with an empty value. I don't really understand what I am doing wrong here.

var str = $('#tool').html();
var res = str.match(/.{1,2}/g);

$.map(res, function(value) {
    if (value.length == 0) {
        return;
        }
    $("div#tool").append('<img src="Images/Woods/' + value + '.png" />');
});

Upvotes: 1

Views: 88

Answers (2)

CptRobby
CptRobby

Reputation: 1521

jQuery Map is not what you want to use here since you are not trying to create a new array.

You should instead use a simple for loop.

var str = $('#tool').html(); //Note that .text() might actually work better here
                             //if you don't want any html tags.
var res = str.match(/.{1,2}/g);

for (var i = 0; i < res.length; i++) {
    var value = res[i];
    if (value.length > 0) {
        $("div#tool").append('<img src="Images/Woods/' + value + '.png" />');
    }
}

I'm also not certain about your regex (it matches whitespace characters, it will grab matches in chunks of 1 or 2 characters, etc), but since I know nothing about what you're using it on, I'll leave that to you.

I hope that helps. :)

Upvotes: 1

gaetanoM
gaetanoM

Reputation: 42044

The regex:

/.{1,2}/g

matches any word (max 2 chars) containing any character, included the space.

In order toi avoid the empty string matches you need to change:

if (value.length == 0) {

adding before a trim:

value = value.trim();

An example:

$.map(" 123 4 5 5 a a ".match(/.{1,2}/g), function(value) {
  value = value.trim();
  if (value.length > 0) {
     $("div#tool").append('< img src="Images/Woods/' + value + '.png" /><br/>');
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<div id="tool"></div>

Upvotes: 0

Related Questions