用JavaScript包装文本 [英] Wrap Text In JavaScript
问题描述
我是JavaScript和jQuery的新手。
I am new to JavaScript and jQuery.
我在JavaScript中有一个名为 str
的变量,它包含很长的文本,比如
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".
我想将它包装并分配给相同的变量 str
在正确的位置插入正确的 \ n
或 br /
标签。
I want to wrap it and assign it to the same variable str
by inserting the proper \n
or br/
tags at the correct places.
我不想使用CSS等。你能告诉我如何在JavaScript中使用适当的函数来实现它,它需要 str
并返回正确的格式化文本?
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?
类似于:
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...
推荐答案
这应该在最近的maxChar空格处插入换行符:
This should insert a line break at the nearest whitespace of maxChar:
str = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It w as popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.";
str = wordWrap(str, 40);
function wordWrap(str, maxWidth) {
var newLineStr = "\n"; done = false; res = '';
do {
found = false;
// Inserts new line at first whitespace of the line
for (i = maxWidth - 1; i >= 0; i--) {
if (testWhite(str.charAt(i))) {
res = res + [str.slice(0, i), newLineStr].join('');
str = str.slice(i + 1);
found = true;
break;
}
}
// Inserts new line at maxWidth position, the word is too long to wrap
if (!found) {
res += [str.slice(0, maxWidth), newLineStr].join('');
str = str.slice(maxWidth);
}
if (str.length < maxWidth)
done = true;
} while (!done);
return res + str;
}
function testWhite(x) {
var white = new RegExp(/^\s$/);
return white.test(x.charAt(0));
};
这篇关于用JavaScript包装文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!