我想在每69个字符后在文本区域添加换行符。我不想在中间剪词。如果拆分发生在单词的中间,则取整个单词并放入下一行。样本句如下:
var sample_txt = "I THOUGHT IT WAS A SIMPLE CONCEPT \nAND DIDN'T FEEL CODE WAS REQUIRED. THE ANSWERS SO FAR SEEM TO HAVE UNDERSTOOD MY EXPLANATION AND SO I AM TRYING THEIR SOLUTIONS NOW. IF I DON'T HAVE ANY JOY I'LL POST SOME CODE. MY IMPLEMENTATION IS ACTUALLY MUCH MORE COMPLEX \nI THOUGHT IT WAS A SIMPLE CONCEPT AND DIDN'T FEEL CODE WAS REQUIRED. THE ANSWERS SO FAR SEEM TO HAVE UNDERSTOOD MY EXPLANATION AND SO I AM TRYING THEIR SOLUTIONS NOW. IF I DON'T HAVE ANY JOY I'LL POST SOME CODE. MY IMPLEMENTATION IS ACTUALLY MUCH MORE COMPLEX";
$(document).on('blur', 'TEXTAREA', function () {
var arr_lines = sample_txt.split('\n'),
char_limit = 69,
txt_val = [];
for(var i = 0; i < arr_lines.length; i++){
if(arr_lines[i].length > char_limit){
var patern = new RegExp('(.{' + (char_limit-1) + '})', 'gi'),
arr_txt = arr_lines[i].replace(patern, "$1\n");
$.each(arr_txt.split('\n'), function(i,vl){
txt_val.push(vl.trim());
});
}else{
txt_val.push(arr_lines[i].trim());
}
}
this.value = txt_val.join('\n');
});
该字符串还包含用户输入的换行符。我是基于'\ n'分割它们然后计算字符并在字符超出限制时再次拆分它们。输出应如下:
I THOUGHT IT WAS A SIMPLE CONCEPT
AND DIDN'T FEEL CODE WAS REQUIRED. THE ANSWERS SO FAR SEEM TO HAVE
UNDERSTOOD MY EXPLANATION AND SO I AM TRYING THEIR SOLUTIONS NOW. IF
I DON'T HAVE ANY JOY I'LL POST SOME CODE. MY IMPLEMENTATION IS
ACTUALLY MUCH MORE COMPLEX
I THOUGHT IT WAS A SIMPLE CONCEPT AND DIDN'T FEEL CODE WAS REQUIRED.
THE ANSWERS SO FAR SEEM TO HAVE UNDERSTOOD MY EXPLANATION AND SO I
AM TRYING THEIR SOLUTIONS NOW. IF I DON'T HAVE ANY JOY I'LL POST
SOME CODE. MY IMPLEMENTATION IS ACTUALLY MUCH MORE COMPLEX
我在stackoverflow.com上查看了一些示例,但我发现的大多数示例中,他们只是将字符限制在一行中。他们没有把这个词放在下一行。
请建议。
答案 0 :(得分:1)
Perl有替换运算符,对于这个问题,它将是
首先删除字符串中的换行符
s/\n//g
然后在69个或更少字符后跟空格或在字符串末尾添加新行
s/(.{1,69})(?:$| )/$1\n/g
最多匹配69个字符和空格,后跟字符串末尾或空格。然后,它会在捕获的$1
文本后面的地方放置换行符。
g修饰符告诉它全局执行此替换(在整个字符串上)。但是,这会在字符串的最后放置换行符,我不知道这是否是您需要的。
结果如下。
我认为它是一个简单的概念,并且需要解决所需的代码。 所以我们很快就会解释我的解释 现在尝试他们的解决方案。如果我没有任何欢乐,我会发布一些信息 码。我认为,我的实施实际上要复杂得多 是一个简单的概念,并且需要解决相关的代码问题。答案 因此,我已经开始了解我的解释,所以我正在尝试 他们的解决方案现在。如果我不感兴趣,我会发布一些代码。 MY 实施实际上更加复杂
但是,如果您想保留原始换行符,请执行以下操作:
我认为它是一个简单的概念
AND DIDN&T;感觉代码是必需的。所以有远见的答案 理解我的解释,所以我现在正在尝试他们的解决方案。如果 我不喜欢我发布了一些代码。我的实施是 实际上更复杂
我认为它是一个简单的概念,并且需要解决所需的代码。 所以我们很快就会解释我的解释 现在尝试他们的解决方案。如果我没有任何欢乐,我会发布一些信息 码。我的实施实际上更加复杂
这个代码会更难。
s/(.{1,69})(?:(?=\n)|$| )/$1\n/g
更新:在看到带有所需输出的已修改帖子后,我会看到您想要的内容。提供这些结果的正则表达式是
s/(.{1,69})(?:\n|$| )/$1\n/g
(忽略我上面给出的解决方案)。
对于jquery的Update2:,我真的不知道,语法需要(在对web进行一些搜索之后),我认为我发现了正确的溶液
this.value = sample_txt.replace(/(.{1,69})(?:\n|$| )/g, "$1\n");
答案 1 :(得分:0)
由于它是textarea,您可以使用cols
属性指定每行所需的字符数。这也处理用户输入换行符的情况。
默认情况下,此值在HTML5中为20(参考:https://developer.mozilla.org/en/docs/Web/HTML/Element/textarea#attr-cols)
示例代码:
<textarea cols="69"> <!--Maximum of 69 characters when there are spaces in the text-->
</textarea>
如果您想以编程方式执行此操作,请参阅以下有关 Word Wrap问题的文章 http://www.geeksforgeeks.org/dynamic-programming-set-18-word-wrap/