Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript split string at 160 characters and add counter?

I am looking to split a string into multiple strings at 160 characters I thought easy enough var splits = myString.split(160);

but apparently that doesn't work anyway.

The other point is that I want to add a counter (android sms style).

so lets say we have this example string (237 characters)

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.

The final output should be

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)

Now if there was always going to be 9 or less messages I could just do

//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+')';

but the issue is that there could be anywhere up to 15 messages, so the amount of characters appended on the end is inconsistent (we want to keep the character count as low as possible to 0 padding numbers less than 10 is not an option).

How can I do this?

like image 532
Hailwood Avatar asked Apr 25 '26 17:04

Hailwood


1 Answers

http://jsfiddle.net/Lobstrosity/nwaYe/

It will cut off at 160 * 15 characters (since you implied that 15 was the limit). It sets both of those numbers as variables up top so you can fiddle with either one.

Update

New fiddle: http://jsfiddle.net/Lobstrosity/nwaYe/2/

It's ugly...but it works...

  1. It figures out if the y in (x/y) is going to be one digit or two.
  2. It uses a placeholder in the indicators while it builds up the actual message.
  3. It replaces the placeholders.
  4. Finally, it splits on charLimit.

I hope someone else figures out a cleaner way to do this...

like image 152
Lobstrosity Avatar answered Apr 27 '26 08:04

Lobstrosity



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!