nodejs 截断字符串_将JavaScript(nodeJS)字符串拆分为固定大小的块

// define string variable

var string = "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 was 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"

function sliceMyString(str){

// initialize array (not required but verbose)

var slices = [];

// while string is not empty

// take 140 characters

// check witch one was the last space or if the end of the line is reached

// then => push them in slices

// then => remove them from the string

while(str != ''){

var lastSpace = 0;

for(var i = 0; i < str.length && i < 140; i ++){

if(str[i] == ' '){

lastSpace = i;

}

if(i == str.length - 1){

lastSpace = str.length;

}

}

// insert into array (including trailing space, see below the codeblock)

slices.push(str.slice(0, lastSpace));

str = str.slice(lastSpace);

}

// just logging the variables in the slices array

slices.map(function(slice){

console.log(slice);

});

}

sliceMyString(string);

如果要删除尾随空格,可以使用 trim() :

slices.push(str.slice(0, lastSpace).trim());

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值