And*_* SK 3 javascript regex string jquery substr
我有一个长字符串需要切成数组内的单独块,预定义的长度限制块.一些规则适用:
原文:我的时间完全没有受到重视.您可以在这间客房内运营整个公园,最少有3天的工作人员.您认为那种自动化很容易吗?还是便宜?你知道有谁可以联网8台连接机器并调试200万行代码,以便我为这份工作买单吗?因为如果他能让我看到他试试.
结果与当前代码 ["我完全","在我的时间中没有得到认可",".你可以运行这整个","从这个房间停放","最小的工作人员,最多","3天.你认为","有点自动化是","sy?还是便宜?你知道","任何可以联网的人,"8个连接机器","调试200万行",我的出价代码" ,"为了这份工作?因为如果","我可以看到h","我试试."]
...它应该居然是:
["我完全","在我的时间里没有得到赏识.","你可以运行这一整体","从这个房间停放","最少3"的工作人员,"几天.你认为那种","自动化很容易?","或便宜?你知道任何人","谁可以网络8","连接机器和","调试200万行","代码为我竞标",这项工作?因为如果他","我想看到他","试试."]
如您所见,我仍然遇到第2和第3条规则的问题.
这是我目前的代码(您可以在jsfiddle中查看工作演示):
function text_split(string, limit, pos, lines) {
//variables
if(!pos) pos = 0;
if(!lines) lines = [];
var length = string.val().length;
var length_current;
//cut string
var split = string.val().substr(pos, limit);
if(/^\S/.test(string.val().substr(pos, limit))) {
//check if it is cutting a word
split = split.replace(/\s+\S*$/, "");
}
//current string length
length_current = split.length;
//current position
pos_current = length_current + pos;
//what to do
if(pos_current < length) {
lines.push(split);
return text_split(string, limit, pos_current, lines);
} else {
console.log(lines);
return lines;
}
}
$(function(){
$('#button').click(function(){
text_split($('#textarea'), 25);
});
});
Run Code Online (Sandbox Code Playgroud)
演示的html表单:
<textarea id="textarea" rows="10" cols="80">I am totally unappreciated in my time. You can run this whole park from this room with minimal staff for up to 3 days. You think that kind of automation is easy? Or cheap? You know anybody who can network 8 connection machines and debug 2 million lines of code for what I bid for this job? Because if he can I'd like to see him try.</textarea>
<button id="button">demo</button>
Run Code Online (Sandbox Code Playgroud)
最多25个字符的示例,您可以使用此模式:
/\S[\s\S]{0,23}\S(?=\s|$)/g
Run Code Online (Sandbox Code Playgroud)
代码示例:
var text = " I am totally unappreciated in my time. You can run this whole park from this room with minimal staff for up to 3 days. You think that kind of automation is easy? Or cheap? You know anybody who can network 8 connection machines and debug 2 million lines of code for what I bid for this job? Because if he can I'd like to see him try.";
var myRe = /\S[\s\S]{0,23}\S(?=\s|$)/g;
var m;
var result = new Array();
while ((m = myRe.exec(text)) !== null) {
result.push(m[0]);
}
console.log(result);
Run Code Online (Sandbox Code Playgroud)
注意:如果需要动态选择最大大小,则必须使用备用语法来定义RegExp对象:
var n = 25;
var myRe = new RegExp("\\S[\\s\\S]{0," + (n-2) + "}\\S(?=\\s|$)", "g");
Run Code Online (Sandbox Code Playgroud)
图案细节:
\S # a non-space character (it is obviously preceded by a space
# or the start of the string since the previous match
# ends before a space)
[\s\S]{0,23} # between 0 or 23 characters
\S(?=\s|$) # a non-space character followed by a space or the end of the string
Run Code Online (Sandbox Code Playgroud)