0
var SPECIAL_CHARS   = Array("\x5B", "\x5C", "\x5D", "\x5E", "\x7B", "\x7C", "\x7D", "\x7E", 8364, 49792, 14844588, '�', '%', '/', '&','�','!','"','(',')','=','[','\\',']','^','{','|','}','~');
var dynamic_variables = Array("${nome}");

function charUsed(el) {
    var base                    = el;
    var count                   = base.val().length;
    var chars                   = base.val().split("");
    var numberOfSpecialChars    = 0;
    for (var k=0; k<chars.length; k++) {
        if ($.inArray(chars[k], SPECIAL_CHARS) > -1) {
            numberOfSpecialChars++;
        }
    }

    if($.inArray(base.val(),dynamic_variables) != -1)
    {
        numberOfSpecialChars = numberOfSpecialChars+40;
    }

    return count + numberOfSpecialChars;
} // function

Basically, I need to count the textarea length and if this contains some special char (array SPECIAL_CHARS) count X 2 (till here, all goes right).

Now I need to add some other words (no more chars), like ${nome}

Pseudocode:

if an element of array is in base.val(), add 40 to the numberOf SpecialChars

Of course, my code doesn't function.

2 Answers 2

1

You can loop through the elements of dynamic_variables Array and check they are present in the main string by using Array.indexOf(). If so add 40.

instead of

if($.inArray(base.val(),dynamic_variables) != -1)
{
    numberOfSpecialChars = numberOfSpecialChars+40;
}

do

for(var i=0;i<dynamic_variables.length;i++)
{
    if(base.val().indexOf(dynamic_variables[i]) != -1) {
        numberOfSpecialChars += 40;
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

var SpecialChars = ['\x5B', '\x5C', '\x5D', '\x5E', '\x7B'];
var SpecialWords = ['foo', 'bar'];

function count(text)
{
  var result = text.length;
     
  // more effective lookup on big text and special char list
  var charLookup = SpecialChars.reduce(function(r, v)
  {
    r[v] = true;
    return r;
  }, {});
  
  // count special chars
  result += text.split('').reduce(function(r, v)
  {
    if(v in charLookup)
    {
      r += 1;
    }
    return r;      
  }, 0);
    
  // count special words
  result += SpecialWords.reduce(function(r, v)
  {
    r += (text.split(v).length - 1) * 40;   
    return r;
  }, 0);    
     
  return result;
}

var result = count(document.getElementById('text').value);
console.assert(result == 'bar some } text [ bar'.length + 2 * 1 + 2 * 40);
document.getElementById('result').innerHTML = result;
<textarea id='text'>bar some { text [ bar</textarea>
<div>Result: <span id='result'></span></div>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.