Home > Software design >  How to count characters in an textarea with some characters counting as double ? (javascript)
How to count characters in an textarea with some characters counting as double ? (javascript)

Time:11-21

I would like to count the characters of a textarea field but some characters like "é, è, €, ..." counting for two. I have this special need for sending SMS plateform and SMS are limited to 160 characters but some count as double.

I've found many solutions on enter image description here

Now I have updated my answer so you can count all characters and also count all duplicate words so now you can update the rest of the scrip accordingly.

CodePudding user response:

You can use regex to count the number of matches to irregular characters. Here's an example. It will count all of the occurances of letter t. Now, you can use regex to count all specific characters that you need or do the opposite and count only the regular characters.

const str = 'some text';
const count = (str.match(/t/g) || []).length;
console.log(count);

Let's assume you got a number of regular characters numRegular. Then you can use str.length to get the full number of characters numFull, then the number of irregular characters will be numIrregular = numFull - numRegular, and you can get the number you want like that num = numIrregular*2 numRegular and use it with whichever implementation of javascript code you would like.

  • Related