通过添加break重新格式化javascript中的字符串
reformatting a string in javascript by adding break ?
我正在尝试用javascript创建一个函数,该函数将一个文本字符串作为参数,然后通过在字符串中添加'n
来格式化它,这将形成段落。
- 每个段落的长度只能是32个字符
- 当我进入下一段时,我必须确保单词不会被切成两半。"
示例字符串:
"If we listened to our intellect, we'd never have a love affair. We'd never have a friendship. We'd never go into business, because we'd be cynical. Well, that's nonsense. You've got to jump off cliffs all the time and build your wings on the way down."
后格式应该像:
If we listened to our intellect, 'n
we'd never have a love affair. 'n
We'd never have a friendship.'n
We'd never go into business, 'n
because we'd be cynical. Well, 'n
that's nonsense. You've got to 'n
jump off cliffs all the time and 'n
build your wings on the way down"
我不确定我将如何处理这个问题,我也不希望有人能解决整个解决方案,我只想要一个起点,我在如何处理空格和单词以及何时将插入字符串方面遇到了困难。
这里有一个适合您的算法:
take your string; chop it up in two pieces: left (first 32 chars), right (the rest)
while right != empty
if length(left) == 32
while last character of left != space
take last char off of left, prepend it to right
print left
new left = first 32 chars of right; right = rest
end while
您可以做一个简单的循环跟踪,跟踪自上一个换行符以来(或自第一行的文本开始以来)遇到的字符数。一旦该值超过32,则迭代回第一个空间,并将其替换为'n
。想想如果一个单词超过32个字符该怎么办。
以下正则表达式对我有效:
str.match(/.{1,32}('s+|$)/g).join("'n");
演示:http://jsfiddle.net/PZxNK/
相关文章:
- 可变大小的JavaScript字符串如何成为基元类型
- 如何将angularjs中的javascript字符串输出为循环数组
- 如何使用gump任务将html转换为javascript字符串
- 替换变量时,JavaScript字符串replace()不起作用
- 如何替换JavaScript字符串中除字母和数字之外的所有内容(空格/符号)
- 如何从django中的url解析javascript字符串
- 拆分javascript字符串以获得所需的值
- 使用Bootstrap'在Javascript字符串中的popover插件
- 如何替换javascript字符串中的前三个连字符
- 将JavaScript字符串转换为整数
- jquery/javascript字符串中的撇号
- 正在对java中的javascript字符串进行转义
- 如何在Javascript字符串中添加vaule
- Javascript:字符串中有效的基于数组的替换
- 具有负值的Javascript字符串.slice()
- javascript字符串替换$1(如果它是某个值)
- 将子函数的JavaScript字符串转换为实际函数
- JavaScript字符串中的换行符也保存为.txt
- 将Javascript字符串var传递给HTML href标记
- JavaScript 字符串字母和数字检查