2013-04-11 82 views
0

我有一个包含多个条目的数组。其中一些在开始时包含@。这是一个数组的例子:如何检查数组中的@(at),并在检查后删除此符号

if(linesArray[i] === '@'){ 
    $('#test').append('<li class="string_with_at">'+linesArray[i]+'</li>'); 
    }else{ 
    $('#test').append('<li class="string_no_at">'+linesArray[i]+'</li>'); 
    } 

我的问题是

some string 
@another string 
@one more string 
the best string 
string with [email protected] 

验证和编组我使用的这部分代码(仅@检查现在):

  1. 如何我可以检查@排队开始第一组吗?
  2. 如何从结果(“礼” + linesArray +“/李”)删除这个符号 - 5月,只留下类明白,这是一个@

回答

1

怎么样:

if(linesArray[i][0] === '@') { //checking the first symbol 
    //remove first element from result 
    $('#test').append('<li class="string_with_at">'+linesArray[i].substring(1)+'</li>'); 
} 
else { 
    $('#test').append('<li class="string_no_at">'+linesArray[i]+'</li>'); 
} 
+0

出于兼容性原因,最好使用'.charAt(0)'而不是'[0]' – TheBrain 2013-04-11 19:13:01

+0

并不令人惊讶,IE7不支持它。感谢您的评论! – 2013-04-11 19:36:59

+0

令人惊叹!非常感谢! – 2013-04-12 08:48:13

1

函数删除 '@' 如果在位置0,并返回新格式的字符串:

removeAt = function(s){ 
    if(s.charAt(0) == '@') 
     return s.substring(1); 
    return s; 
} 
0

这应该做的伎俩:

function addElement (val) { 
    var match = val.match(/^(@)(.*)/), 
     at = match[1], 
     str = match[2], 
     li = $('<li/>').html(str) 

    li.addClass('string_' + (at ? 'with' : 'no') + '_at'); 

    $('#test').append(li); 
} 

linesArray.forEach(addElement);