0

I have a string that is supposed to go into a text message, however the text keeps going off the box, i want to wrap the text in the div. I want to split the string so that every 17 characters or so, a
tag is inserted so that it moves to the new. I would need to split the string along the spaces to keep the words whole, but would need to make sure the total characters in a line don't go over 17.

Are there any other methods that i am not seeing? maybe a wrap text feature on Jquery?

right now i do the following code:

 var newMessageArr = message.match(/.{1,15}/g);
var splitMessage = '<li class="replies"><p>' + newMessageArr[0];


    for (var i = 1; i < newMessageArr.length - 1; i++) {
        splitMessage += '<br>' + newMessageArr[i];
    }
    splitMessage += '</p></li>';

$(splitMessage).appendTo($('.messages ul'));

this makes the message into an array, and inserts a br tag at the given interval, the only problem is that it cuts the words off.

Any help is much appreciated, new to front end so go easy if there is something obvious that im missing...

2 Answers 2

1

I think that CSS word-break property can help you: https://www.w3schools.com/cssref/css3_pr_word-break.asp

Run the following example taken from w3school:

<!DOCTYPE html>
<html>
<head>
<style>
p {
    width: 140px; 
    border: 1px solid #000000;
}

p.a {
    word-break: normal;
}

p.b {
    word-break: keep-all;
}

p.c {
    word-break: break-all;
}
</style>
</head>
<body>
<h1>The word-break Property</h1>

<h2>word-break: normal (default):</h2>
<p class="a">Thisissomeveryveryverylong word. Words will break according to usual rules.</p>

<h2>word-break: keep-all:</h2>
<p class="b">Thisissomeveryveryverylong word. This text will-break-at-hyphens.</p>

<h2>word-break: break-all:</h2>
<p class="c">Thisissomeveryveryverylong word. This text will break at any character.</p>

</body>
</html>

Sign up to request clarification or add additional context in comments.

Comments

1

Or you can use this regular expression:

var message='This is a really long message that needs to be broken into several lines of not more than 17 characters in length.';
console.log(message.match(/(.{1,16})(?:$| +)/g).join('\n'))

Obviously, if you want to append the resulting string to a <div class="message"><ul>... structure you'll will need to join the pieces with <br>:

$('.messages ul').append('<li>'+message.match(/(.{1,16})(?:$| +)/g).join('<br>')+'</li>');

1 Comment

does "\n" work within the element of say a <p> tag, or does it need <pre> tags to work? thanks

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.