Javascript迭代字符串寻找多个字符集

时间:2017-06-23 01:12:34

标签: javascript regex string loops

好的,所以我知道如何做一个标准循环迭代字符串来查找匹配单个字符或单词的字符或单词,但在这个例子中,我有多个我正在寻找的字符集。有些是字母,有些是字符(包括受保护的字符)。我不能把它分成空格或类似的单词数组,因为字符集可能没有空格,所以不会拆分。我怀疑我将不得不做一个正则表达式,但我不知道如何设置它。这基本上是我正在尝试做的伪代码,我很欣赏任何有关如何前进的提示。我很抱歉,如果这是一件容易的事情,我很想念它,我仍然在研究我的javascript。

伪代码:

var string = "This *^! is abdf random&!# text to x*?ysearch for character sets";
var tempSet = [];

// start a typical for loop
for(string.length bla bla...){
  // look for one of those four character sets and if it hits one 
  if(foundSet == "abdf" | "x*?y" | "*^!" | "&!#")
    // push that character set to the tempSet array
    tempSet.push(foundSet);
    // continue searching for the next set until the string is done 

console.log(tempSet);  
//expected result = ["*^!", "abdf", "&!#", "x*?y"]

并且所有集合都按照它们出现在字符串

中的顺序在数组中

显然有更多,但我能处理的那部分。就是这条线

if(??? == "abdf" | "x*?y" | "*^!" | "&!#")

我真的不知道如何解决。我怀疑它应该是某种正则表达式,但是你有一个像这样的正则表达式在做if语句时?我用|做了它们做地图/替换时,我从来没有在循环中使用正则表达式。我也不知道如何让它一次搜索多个角色。一些字符集是3,有些是4个字符长。

如果您对如何以更简单的方式处理此问题提出任何建议,我将不胜感激,这将是非常棒的。

谢谢!

4 个答案:

答案 0 :(得分:1)

我认为您正在寻找的是include()函数。

var sample = "This *^! is abdf random&!# text to x*?ysearch for character 
sets";
var toSearch = ["*^!", "abdf", "&!#", "x*?y"];
var tempSet = [];

for (var i = 0; i < toSearch.length; i++) {
    if (sample.includes(toSearch[i]){
        tempSet.push(toSearch[i]);
    }
}

console.log(tempSet);  
//expected result = ["*^!", "abdf", "&!#", "x*?y"]

这样你就可以迭代你正在搜索的任何字符串的整个数组,并将所有匹配的元素推送到tempSet。

注意:区分大小写,因此请务必相应地考虑您的支票。

答案 1 :(得分:1)

如果我能够的话,我会将此作为对Kevin答案的评论添加,但如果您需要IE支持,您还可以检查searchString.indexOf(searchToken)!== -1。

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf

答案 2 :(得分:1)

您可以使用正则表达式。只需将所有字符串列为|分隔的替代字词。在正则表达式中具有特殊含义的字符(例如*?^$)将需要使用\进行转义(您可以安全地逃脱任何非字母数字字符 - 有些将是多余的。)

var string = "This *^! is abdf random&!# text to x*?ysearch for character sets";
var tempSet = string.match(/abdf|x\*\?y|\*\^!|&!#/g);

console.log(tempSet);

如果您需要循环,可以循环调用RegExp.prototype.exec()

var string = "This *^! is abdf random&!# text to x*?ysearch for character sets";
var regex = /abdf|x\*\?y|\*\^!|&!#/g;
var tempSet = [];
while (match = regex.exec(string)) {
  tempSet.push(match[0]);
}
console.log(tempSet);

答案 3 :(得分:1)

比Barmar优秀的RegEx更多的手动方法,但是组合起来很有趣并且可以更清楚地显示这些部分:

var text = "This *^! is abdf random&!# text to x*?ysearch for character sets",
    detect = ["abdf", "x*?y", "*^!", "&!#"],
    haystack = '',
    found = [];

text.split('').forEach(function(letter){
    haystack += letter;
    detect.forEach(function(needle){
        if (haystack.indexOf(needle) !== -1
             && found.indexOf(needle) === -1) {
            found.push(needle);
        }
    });
});

console.log(found);