4

I have a looping function creating:

<li id="id1" name="Tag1,Tag2,Tag3">
<li id="id2" name="Tag1,Tag2,Tag3">


$.each(data.posts, function(i, post){       
 $('<li >', {id: this.id , name: post.tags})  
});

How do I replace the commas between the tags with spaces. Also is there a way I can send the tags to a "class" attribute instead of "name". It seems to not work in Safari.

4 Answers 4

10

What you probably want is this:

$('<li >', {id: this.id , className : post.tags.join(' ')})

By default, when you cast an array to a string, it get concatenated with commas as you have seen. Using join() will solve the problem.

Also, class is a reserved keyword in all browsers (though some won't throw an error if you use it), so the attribute you should use for setting the class is called className

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

3 Comments

+1, class is a future reserved word all of them should be avoided as identifiers...
The above assumes tags is an array (which, apparently it is in Alex's case). If tags is a string, you would could do either "tags.split(',').join(' ')" or "tags.replace(/,/g, ' ')"
You can do 'class' as the key as well, with quotes
1

Try this:

$.each(data.posts, function(i, post){ 
 $('<li >', {id: this.id , name: post.tags.join(' ')});  
});

Comments

0
$.each(data.posts, function(i, post) {
    $('<li >', {id: this.id , name: post.tags.replace(/[,]/g, ' ')})
});

Comments

-1

Use the replace string method (as mentioned in other replies) to replace the commas.

As for the classes, add them like this:

$('<li >', {id: this.id }).addClass(post.tags.join(' '));

2 Comments

This will only replace the first ','. To replace all, you need to pass a regex with the 'g' option set as the first arg, as in my comment above. (And, of course, this also assumes tag is a String, not an Array)
oops, I hadn't actually looked at that part, as mentioned, I copied the code from above. The addClass is the correct way to add classes, as opposed to a "className" attribute, which is what I was demonstrating. I have adjusted the code to properly concat the tags, sorry about that.

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.