Aaron
Aaron

Reputation: 181

How to split string based on number of characters using javascript

I'm trying to take one string and split it into different chunks, and place it inside divs. Here's my code:

var simple = '<?php echo $hallo; ?>';     
var $div = $('#mybook');

if ($div.text().length > 50) {
    var limit = simple.lenght = 10;
    $(simple.split(limit)).each(function() {
        $('#mybook').append('<div>'+this+'</div>')
    });
}

Thank you, any help is appreciated.

Upvotes: 0

Views: 500

Answers (2)

tftd
tftd

Reputation: 17032

Something like this should do the work:

<script type="text/javascript">
var simple = '<?php echo $hallo; ?>';
var $div = $('#mybook');
if($div.text().length > 50) {
    var limit = simple.lenght = 10;
    var regex = new RegExp('.{1,'+limit+'}','g')
    $(simple.match(regex)).each(function(key,val){
        $('#mybook').append('<div>'+val+'</div>')
    })
}
</script>

Upvotes: 2

bukart
bukart

Reputation: 4906

just split your string with a regex, not with split

$(simple.match('/.{'+limit+'}|.{,'+(limit-1)+'}$/g')).each(function() {

    $('#mybook').append('<div>'+this+'</div>')

});

Upvotes: 1

Related Questions