JQuery - Split String (For Each)
28,578
Solution 1
You can use join()
for that
var data = $('.availability').text();
var arr = data.split('•');
$('.availability').html("<li><i class='icon-check twentytwo color'></i><span>"
+ arr.join("</span></li><li><i class='icon-check twentytwo color'></i><span>")
+ "</span></li>");
Solution 2
You can loop your array by using the $.each
function.
But instead of using html()
which will override your HTML, you should append()
the items.
var data = $('.availability').text();
var arr = data.split('•');
$.each( arr, function( index, value ) {
$('.availability').append("<li><i class='icon-check twentytwo color'></i><span>" + value + "</span></li>");
});
Author by
Bryan Counts
Updated on September 17, 2020Comments
-
Bryan Counts almost 4 years
Current Code Below - I have to copy and paste each
arr[0], arr[1], arr[2]
. However, in the future I may have more or less array options and would like the code to auto update itself without needing to alter my code.Basically, I want to create a "for-each" situation for each list item:
<li><i class='icon-check twentytwo color'></i><span>" + arr + "</span></li>
Current Code:
var data = $('.availability').text(); var arr = data.split('•'); $('.availability').html("<li><i class='icon-check twentytwo color'></i><span>" + arr[0] + "</span></li><li><i class='icon-check twentytwo color'></i><span>" + arr[1] + "</span></li><li><i class='icon-check twentytwo color'></i><span>" + arr[2] + "</span></li>");
ANSWER = All of these would have worked in various situations. I selected my answer based on the fact that I am using a handlebar template making some of these code snippets not usable for my project.