1

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" />');
});

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

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>

1 Comment

It works perfectly now with trim method and I'll see I also need to change the regex to avoid other problems, Thanks allot!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.