简体   繁体   中英

Count of multiple substrings in JavaScript string

I am receiving a tokenized string from the server in the form of status---delimiter---status where I may have up to 1000 statuses. There are only 6 different possible values for status. I am trying to find a way to search for all 6 at once and that gives me a count of each. I've come up with several less optimum ways of solving the issue but the best I could think of still effectively makes 2 full passes on the string and involves several substeps. I looked at regX .match and capture groups but couldn't seem to find any way to make that work better then one status at a time. I realize the performance difference wont be noticeable but now I just want to know, since in theory this should be doable (though maybe not with JavaScripts regX).

Example Set of statuses: [red,blue,green,orange,purple,pink] Delimiter (I can chose this): | String: red|purple|green|red|blue|orange|purple|blue

Result: [red: 2, blue: 2, green: 1, orange: 1, purple, 2, pink 0]

使用此答案中的 strtok迭代字符串一次,依次拉出每个“标记”(状态值),并随时增加计数。

Your question is a bit unclear. This is what I'm assuming you're attempting to do (ie. ---delimiter--- is wrapped in a status):

var string = 'status1---delimiter---status1 asdf status1---delimiter---status1 asdf asdf fdsa status3---delimiter---status3 asdf status1---delimiter---status1 fdsa status1---delimiter--- asdf status5---delimiter---status5 status5---delimiter---status5 asdf status6---delimiter---status6 asdffdsa';
var matches = {}, re = /(status1|status2|status3|status4|status5|status6)---delimiter---\1/g, match;
while (match = re.exec(string)) {
    if (!matches.hasOwnProperty(match[1])) {
        matches[match[1]] = 1;
    } else {
        matches[match[1]] += 1;
    }
}
/*
 * matches = {
 *     status1: 3,
 *     status3: 1,
 *     status5: 2,
 *     status6: 1
 * }
 */

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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