0

i need to check if a textarea contains some special characters, so i need to count them 2 (SMS lenght).

I wrote this piece of code but seems that it doesn't find no special chars, also if write only "€€€"

Could you please help me? Also if you would to rewrite directly function, without problem. Thank tou!

var SPECIAL_CHARS = Array('€', '%'); function charUsed() { var count = $('#text').val().length; var chars = $('#text').val().split(""); var numberOfSpecialChars = 0; if ($.inArray(chars, SPECIAL_CHARS) > -1) { numberOfSpecialChars++; } return count + numberOfSpecialChars; } // function 
4
  • sorry to ask, but if you check for existance of any special-char, why not use regex? Commented Sep 3, 2013 at 15:23
  • 1
    $.inArray takes value, array, not two arrays. Commented Sep 3, 2013 at 15:24
  • @Andrew Whitaker Solved with for (var k=0; k<chars.length; k++) { if ($.inArray(chars[k], SPECIAL_CHARS) > -1) { numberOfSpecialChars++; } } Commented Sep 3, 2013 at 15:39
  • @sineverba if you like your solution, post it as answer and accept it. Commented Sep 3, 2013 at 15:39

2 Answers 2

3

http://jsfiddle.net/KSm7J/

var chars = $('#text').val().match(/[€%]/g).length; alert(chars); 
Sign up to request clarification or add additional context in comments.

1 Comment

Damn... this is simpler than mine... +1
3

A rewrite :

var nbSpecialChars = $('#text').val().split(/[€%]/).length - 1; 

The idea is to make an array of strings, using your special characters as separator :

'some € chars %' => ["some ", " chars ", ""] 

and then use the length of this array to deduce the count of those chars. There are many other (faster) solutions but this one is short.

1 Comment

aaaand he understands what you did.... not... please be so kind to illuminate your answer, and what you did to OP

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.