繁体   English   中英

如果charAt等于字符列表

[英]if charAt equal to a list of characters

我想在Javascript中使用以下内容

如果str.charAt(index)(在集合中){“。”,“,”,“#”,“$”,“;”,“:”}

是的,我知道这一定很简单,但我似乎无法正确理解语法。 我现在拥有的是什么

theChar = str.charAt(i);
if ((theChar === '.') || (theChar === ',') || (theChar === ... )) {
  // do stuff
}

这有效,但必须有更好的方法。

编辑:我做了这个,但不确定它是否良好:

var punc = {
    ".":true,
    ",":true,
    ";":true,
    ":":true
};

if (punc[str.charAt[index]) { ...

使用这些字符定义一个数组,然后只需在数组中搜索。 一种方法是:

var charsToSearch = [".", ",", "#", "$", ";", ":"];
var theChar = str.charAt(i); /* Wherever str and i comes from */

if (charsToSearch.indexOf(theChar) != -1) {
    /* Code here, the char has been found. */
}

您可以使用正则表达式执行此操作:

var theChar = str.charAt(i);
if (/[.,#$;:]/.test(theChar)) {
  // ...
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM