Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
145 views
in Technique[技术] by (71.8m points)

jquery - Wrap Text In JavaScript

I am new to JavaScript and jQuery.

I have a variable named as str in JavaScript and it contains very long text, saying something like

"A quick brown fox jumps over a lazy dog". 

I want to wrap it and assign it to the same variable str by inserting the proper or br/ tags at the correct places.

I don't want to use CSS etc. Could you please tell me how to do it with a proper function in JavaScript which takes the str and returns the proper formatted text to it?

Something like:

str = somefunction(str, maxchar);

I tried a lot but unfortunately nothing turned up the way I wanted it to be! :(

Any help will be much appreciated...

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Although this question is quite old, many solutions provided so far are more complicated and expensive than necessary, as user2257198 pointed out - This is completely solvable with a short one-line regular expression.

However I found some issues with his solution including: wrapping after the max width rather than before, breaking on chars not explicitly included in the character class and not considering existing newline chars causing the start of paragraphs to be chopped mid-line.

Which led me to write my own solution:

// Static Width (Plain Regex)
const wrap = (s) => s.replace(
    /(?![^
]{1,32}$)([^
]{1,32})s/g, '$1
'
);

// Dynamic Width (Build Regex)
const wrap = (s, w) => s.replace(
    new RegExp(`(?![^\n]{1,${w}}$)([^\n]{1,${w}})\s`, 'g'), '$1
'
);

Bonus Features

  • Handles any char that's not a newline (e.g code).
  • Handles existing newlines properly (e.g paragraphs).
  • Prevents pushing spaces onto beginning of newlines.
  • Prevents adding unnecessary newline to end of string.

Explanation

The main concept is simply to find contiguous sequences of chars that do not contain new-lines [^ ], up to the desired length, e.g 32 {1,32}. By using negation ^ in the character class it is far more permissive, avoiding missing things like punctuation that would otherwise have to be explicitly added:

str.replace(/([^
]{1,32})/g, '[$1]
');
// Matches wrapped in [] to help visualise

"[Lorem ipsum dolor sit amet, cons]
[ectetur adipiscing elit, sed do ]
[eiusmod tempor incididunt ut lab]
[ore et dolore magna aliqua.]
"

So far this only slices the string at exactly 32 chars. It works because it's own newline insertions mark the start of each sequence after the first.

To break on words, a qualifier is needed after the greedy quantifier {1,32} to prevent it from choosing sequences ending in the middle of a word. A word-break char can cause spaces at the start of new lines, so a white-space char s must be used instead. It must also be placed outside the group so it's eaten, to prevent increasing the max width by 1 char:

str.replace(/([^
]{1,32})s/g, '[$1]
');
// Matches wrapped in [] to help visualise

"[Lorem ipsum dolor sit amet,]
[consectetur adipiscing elit, sed]
[do eiusmod tempor incididunt ut]
[labore et dolore magna]
aliqua."

Now it breaks on words before the limit, but the last word and period was not matched in the last sequence because there is no terminating space.

An "or end-of-string" option (s|$) could be added to the white-space to extend the match, but it would be even better to prevent matching the last line at all because it causes an unnecessary new-line to be inserted at the end. To achieve this a negative look-ahead of exactly the same sequence can be added before, but using an end-of-string char instead of a white-space char:

str.replace(/(?![^
]{1,32}$)([^
]{1,32})s/g, '[$1]
');
// Matches wrapped in [] to help visualise

"[Lorem ipsum dolor sit amet,]
[consectetur adipiscing elit, sed]
[do eiusmod tempor incididunt ut]
labore et dolore magna aliqua."

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...