如何将json数据中的空格替换为_,并用数据表为每一行添加超链接



在用数据表显示JSON数据之前,我想从后端自定义JSON数据。首先,我想用下划线符号(_(替换artist.name列中的空格((。然后,我想像我的代码一样,用wiki链接来超链接该列中的每一行。

HTML:

<table id="albums" class="table table-striped table-bordered" style="width:100%" >
<thead>
<tr>
<th>Rank</th>
<th>Artist</th>
<th>Album name</th>
<th>Year</th>
<th>Genres</th>
</tr>
</thead>
</table>

数据表JS:

"columns": [
{"data": "rank", "searchable": false},
{
"data": "artist.name".replace(/s+/g, '_'),      // ex: 'The Beatles' => 'The_Beatles'
"name": "artist.name".replace(/s+/g, '_'),
"render": function (data, name) {
data = '<a href= "https://en.wikipedia.org/wiki/' + name + '">' + name + '</a>';  // render to: https://en.wikipedia.org/wiki/The_Beatles
return data;
} 
},
{"data": "name"},
{"data": "year"},
{"data": "genres", "name": "genres.name", "sortable": false},
]

JSON数据:

{
"data": [
{
"DT_RowId": "row_1",
"DT_RowAttr": {
"data-pk": 1
},
"rank": 1,
"name": "Sgt. Pepper's Lonely Hearts Club Band",
"year": 1967,
"artist_name": "The Beatles",
"genres": "Psychedelic Rock, Rock & Roll",
"artist": {
"id": 2,
"name": "The Beatles"
}
},
{
"DT_RowId": "row_2",
"DT_RowAttr": {
"data-pk": 2
},
"rank": 2,
"name": "Pet Sounds",
"year": 1966,
"artist_name": "The Beach Boys",
"genres": "Pop Rock, Psychedelic Rock",
"artist": {
"id": 3,
"name": "The Beach Boys"
}
}  
...      
],
"recordsFiltered": 15,
"recordsTotal": 15,
"draw": 1

}

它不起作用。有人能帮我吗?谢谢

好的,谢谢大家。我用这个零钱把它修好了。

"columns": [
{"data": "rank", "searchable": false},            
{
"data": "artist.name",      
"name": "artist.name",
"render": function (data, type, row, meta) {
data = '<a href= "https://en.wikipedia.org/wiki/' + data.split(' ').join('_') + '">' + data + '</a>';
return data;
}           
},
{"data": "name"},
{"data": "year"},
{"data": "genres", "name": "genres.name", "sortable": false},
]

您可以使用.replace(/ /g,"_");.split(' ').join('_');函数来执行以下操作:在JavaScript中用下划线替换空格?

最新更新