0

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.

5
  • String.split doesn't take a number, it takes a string delimiter that tells the function where to create the chunks. Commented Jan 6, 2013 at 1:18
  • So is there another way to do this? how? Commented Jan 6, 2013 at 1:20
  • It's good practice to end your JS statements with a semicolon ;. Some of your statements end with it, others don't. Commented Jan 6, 2013 at 1:20
  • @Aaron: It depends on exactly what you're trying to do. Could you add an example input string and what the expected output would be? Commented Jan 6, 2013 at 1:21
  • @AndrewWhitaker he's trying to limit the string size to some size. The extra characters would go into a new div. For example let's say there's a limit of 2 characters and a string abcdefghijklmnopqrstuvwxyz. The result should be <div>ab</div><div>cd</div> and so on. At least that's what seems he's looking for.. Commented Jan 6, 2013 at 1:28

2 Answers 2

2

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>
Sign up to request clarification or add additional context in comments.

1 Comment

Ugh, it worked nicely! tbh, this is what i love about this site. Both answers actually worked. Thanks!
1

just split your string with a regex, not with split

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

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

});

Comments

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.