简体   繁体   English

如何使用JavaScript / JQuery创建每个40个字符的自动自动换行

[英]How to create an automatically word wrap each 40 Characters with JavaScript / JQuery

Is it possible to create an automatically word wrap every 40 insert characters with java script? 是否可以使用java脚本每40个插入字符创建一个自动自动换行? I have programmed a jQuery / javascript solution, which used the keyUp event of a textfield: 我编写了一个jQuery / javascript解决方案,它使用了textfield的keyUp事件:

jQuery(textInputfield).keyup(function(event) {      
    var text = jQuery(textInputfield).val();            
    if(text.length == 40){
        text = text + '<br />';
    }    
    var textOutput = jQuery(textOutputField);
    textOutput.empty();
    textOutput.append(text);    
});

I need a more flexible solution for this code: 我需要一个更灵活的解决方案来代码:

if(text.length == 40){
   text = text + '<br />';
}

How can i solve this problem? 我怎么解决这个问题?

A regex solution: 正则表达式解决方案:

var text = jQuery(this).val();
text = text.replace(/.{40}/g, '$&<br/>');

I would suggest against reformatting in this way and instead using a specified width and let the browser make the line break. 我建议不要以这种方式重新格式化,而是使用指定的宽度让浏览器进行换行。

Use a specified width and height: auto 使用指定的widthheight: auto

EDIT: see this fiddle for example http://jsfiddle.net/bf9rJ/ 编辑:看到这个小提琴例如http://jsfiddle.net/bf9rJ/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM