最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - replace commas with spaces from json array - Stack Overflow

programmeradmin1浏览0评论

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 mas 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.

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 mas 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.

Share Improve this question edited Jun 15, 2010 at 2:36 Reigel Gallarde 65.3k21 gold badges125 silver badges142 bronze badges asked Jun 15, 2010 at 2:21 AlexAlex 1532 silver badges10 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 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 mas 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

Try this:

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

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

As for the classes, add them like this:

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

评论列表(0)

  1. 暂无评论