Javascript 以 160 个字符拆分字符串并添加计数器?

标签 javascript jquery string sms

我希望将一个字符串分成多个 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/

它很丑...但它有效...

  1. 它计算出 (x/y) 中的 y 是一位数还是两位数。
  2. 它在构建实际消息时在指示符中使用占位符。
  3. 它取代了占位符。
  4. 最后,它在 charLimit 上拆分。

我希望其他人想出一个更简洁的方法来做到这一点......

关于Javascript 以 160 个字符拆分字符串并添加计数器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7014229/

相关文章:

javascript - 迭代表的行

javascript - 如何使用 jquery 将文本复制到剪贴板?

string - 如何将字符串元胞数组转换为字符串矩阵?

javascript - 出现在我的 javascript 数组中的未识别值

javascript - 如何按值对集合进行排序?

javascript - angularjs指令使用 Controller 作为vm而不是作用域

javascript - 播放和循环文件中的多个视频 (HTML)

javascript - 如何从下到上制作条形图的动画?

Ruby:替换字符串的一部分

c - 如何制作递归函数,将大写字母放在第一个字母和这个 '.' 字符之后