0

I want to insert a line Break after every 55 characters i have made a jquery script but it doesn't work can some one please point me in the right direction

Jquery.js

$(document).ready(function() {
    $('#text_comment').text($(this).val().replace(/([\s\S]{55})/g, '$1<br />'));

});

Index.php

<input type="text" class="comment" id="text_comment"autocomplete="off"time_date="<?php echo $date_shared;?>" 
    username="<?php echo $comment_username;?>"post_id="<?php echo $shared_id2; ?>"placeholder="Write a Comment"/>
kunz
  • 1,063
  • 1
  • 11
  • 27
  • 3
    Possible duplicate of [Add line breaks after n numbers of letters in long words](http://stackoverflow.com/questions/10798734/add-line-breaks-after-n-numbers-of-letters-in-long-words) – Ali Zia Jan 26 '16 at 12:32
  • 1
    why dont use textarea and \n to break ? – Jeremy Jan 26 '16 at 12:33
  • Possible duplicate of [Jquery or javascript to add one line break
    after x amount of characters in a
    ](http://stackoverflow.com/questions/7068653/jquery-or-javascript-to-add-one-line-break-br-after-x-amount-of-characters-i)
    – arc Jan 26 '16 at 12:33
  • http://php.net/manual/en/function.wordwrap.php – GordonM Jan 26 '16 at 12:38
  • 1
    none of them seem to work it just keeps going on and on instead of goin on a new line – kunz Jan 26 '16 at 12:46

2 Answers2

0

Line-breaks are automatically removed from inputs with a type of text.

text: A single-line text field; line-breaks are automatically removed from the input value.

You can use a textarea to display the line breaks:

var myString = '1234567890';
myString = myString.replace(/.{1,2}/g, "$&\n"); //replace 2 with 55 for your example

document.getElementById('text').value = myString; // :(
document.getElementById('textarea').value = myString; // :)
<input type="text" id="text"> <-- line-breaks automatically removed
<br>
<textarea id="textarea" rows="7"></textarea>
pherris
  • 17,195
  • 8
  • 42
  • 58
  • how would i implement this with the `id = text_comment` – kunz Jan 26 '16 at 12:40
  • I see - you want line-breaks inside of a `input type="text"` - for that HTML element, line-breaks are removed. I will update my answer. – pherris Jan 26 '16 at 13:56
0

You can use this approach.

$original = "Sample String.";
$parts = str_split($original, 4); //Replace '4' with '55' afterwards.
$final = implode("<br />", $parts);
Ali Zia
  • 3,825
  • 5
  • 29
  • 77