测试String是否包含构成另一个字符串的所有字符 [英] Test If String Contains All Characters That Make Up Another String

查看:100
本文介绍了测试String是否包含构成另一个字符串的所有字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Javascript来查看某个字符串是否包含构成另一个字符串的所有字符。

I am trying to use Javascript to see if a certain string contains all characters that make up another string.

例如,单词hello包含所有字符构成地狱这个词。此外,单词hellowy包含组成单词yellow的所有字符。

For instance, the word "hello" contains all characters that make up the word "hell." Also, the word "hellowy" contains all characters that make up the word "yellow."

最重要的是,该方法需要工作,而不管两者中的字符顺序如何串。另外,字符数很重要。 Hel并不包含构成地狱的所有角色。这严格指的是字符数:一个需要两个l来制作单词hell而hel只有一个。

Most importantly, the method needs to work irrespective of the order of characters in both string. In addition, the numbers of characters matters. "Hel" does not contain all characters to make up "hell." This refers strictly to the number of characters: one needs two l's to make word "hell" and "hel" only has one.

进一步澄清这个问题,我不担心如果在字符串字符的子字符串组成后留下一些未使用的字符。也就是说,helll仍然应该包含单词hell的所有字母。

Further clarifying the question, I am not worried if I am left with some "unused" characters after the composition of the substring from the characters of the string. That is, "helll" still should contain all letters for the word "hell."

如何有效地完成此操作?也许有一个正则表达式解决方案?速度有点问题,但不是绝对关键。

How can I accomplish this efficiently? Perhaps there is a regex solution? Speed is somewhat of an issue, but not absolutely critical.

推荐答案

你可以使用 每个

You can use every:

function test(string, substring) {
    var letters = [...string];
    return [...substring].every(x => {
        var index = letters.indexOf(x);
        if (~index) {
            letters.splice(index, 1);
            return true;
        }
    });
}

每个都会失败在第一个falsy值中,它不会搜索每个字母。

Every will fail in the first falsy value, then it does not search every letter.

这篇关于测试String是否包含构成另一个字符串的所有字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆