Jquery如何检查数组字符串值是否在textarea中

时间:2014-09-24 11:07:15

标签: javascript jquery arrays

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

基本上,我需要计算textarea长度,如果这包含一些特殊的char(数组SPECIAL_CHARS),则计算X 2(直到这里,一切顺利)。

现在我需要添加一些其他词(不再是字符),例如${nome}

伪代码:

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

当然,我的代码不起作用。

2 个答案:

答案 0 :(得分:1)

您可以循环遍历dynamic_variables数组的元素,并使用Array.indexOf()检查它们是否存在于主字符串中。如果是这样,加40。

而不是

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

for(var i=0;i<dynamic_variables.length;i++)
{
    if(base.val().indexOf(dynamic_variables[i]) != -1) {
        numberOfSpecialChars += 40;
    }
}

答案 1 :(得分: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>