我希望将一个字符串分成多个 160 个字符的字符串,我认为这很简单 var splits = myString.split(160);
但显然这无论如何都行不通。
另外一点是我想添加一个计数器(android sms 样式)。
假设我们有这个示例字符串(237 个字符)
hi there, this message is 237 characters long, which makes it much to long for a single message, this string will be split up into multiple messages... this is actually for an sms application hence the reason we need to split the string.
最终输出应该是
hi there, this message is 237 characters long, which makes it much to long for a single message, this string will be split up into multiple messages... thi(1/2)
s string will be split up into multiple messages... this is actually for an sms application hence the reason we need to split the string.(2/2)
现在,如果总是有 9 条或更少的消息,我就可以做到
//ok, so the next line won't work, but it gets the point across...
var splits = mystring.split(155);
var s = splits.length;
for(var i = 0; i < s; i++)
splits[i] += '('+(i+1)+'/'+s+')';
但问题是任何地方最多可能有 15 条消息,因此末尾附加的字符数量不一致(我们希望将字符数保持在尽可能低的 0 小于 10 的填充数字不是选项)。
我该怎么做?
最佳答案
http://jsfiddle.net/Lobstrosity/nwaYe/
它将在 160 * 15 个字符处 chop (因为您暗示 15 个字符是限制)。它将这两个数字设置为顶部的变量,因此您可以摆弄其中一个。
更新
新 fiddle :http://jsfiddle.net/Lobstrosity/nwaYe/2/
它很丑...但它有效...
- 它计算出
(x/y)
中的y
是一位数还是两位数。 - 它在构建实际消息时在指示符中使用占位符。
- 它取代了占位符。
- 最后,它在
charLimit
上拆分。
我希望其他人想出一个更简洁的方法来做到这一点......
关于Javascript 以 160 个字符拆分字符串并添加计数器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7014229/