admin管理员组

文章数量:1289584

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

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."

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.

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

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

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

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."

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.

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

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

Share Improve this question edited Jul 23, 2016 at 20:29 MadPhysicist asked Jul 23, 2016 at 19:29 MadPhysicistMadPhysicist 5,84113 gold badges49 silver badges121 bronze badges 4
  • ""Hel" does not contain all characters to make up "hell.""? "hel" does contain all characters which prise "hell" . Do you mean by case-sensitivity? – guest271314 Commented Jul 23, 2016 at 19:54
  • No. Only by the quantity of characters. You need two l's to make word "hell" and "hel" only has one. – MadPhysicist Commented Jul 23, 2016 at 19:55
  • Note, that is an important requirement which did not appear to be included at original Question? You should be able to check input string .length is equal to matching string .length – guest271314 Commented Jul 23, 2016 at 19:56
  • I shall add that now. – MadPhysicist Commented Jul 23, 2016 at 19:59
Add a ment  | 

5 Answers 5

Reset to default 5

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;
        }
    });
}

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

If the number of letters matters then maybe something like this:

function test(string, substring) {
    var regexp = new RegExp(substring.split("").sort().map(function(s) { return s + "+"; }).join(""));
    return regexp.test(string.split("").sort().join(""));
}

This is slower than the above answers, but if there is some repetition in the strings then it's possible to cache and get better speed performance than the other answers:

var cache1 = { };
var cache2 = { };
function test2(string, substring) {
    var regexp = cache1[substring];
    if (!regexp) {
        regexp = new RegExp(substring.split("").sort().map(function(s) { return s + "+"; }).join(""));
        cache1[substring] = regexp;
    }

    var string2 = cache2[string];
    if (!string2) {
        string2 = string.split("").sort().join("");
        cache2[string] = string2;
    }

    return regexp.test(string2);
}

Edit, Updated

In addition, the numbers of characters matters. "Hel" does not contain all characters to make up "hell."

You can use a variable to store Boolean value, for..of loop, String.prototype.indexOf() check for, set Boolean variable, break loop if false.

You should also be able include check if input string .length is equal to matching string .length at if condition, set variable to false if the two string .length properties are not equal.

var str = "hell";
var match = "hel";
var bool = true; 
for (var prop of str) {
  if (str.length !== match.length || match.indexOf(prop) === -1) {
    bool = false; break;
  }
};
console.log(bool); // false

Make some training I came up with this thing:

function test(str, substring) {
  var arr_str = str.toLowerCase().split('');
  var arr_substr = substring.toLowerCase().split('');

  return arr_substr.filter(function(each) {
    return arr_str.indexOf(each) === -1;
  }).length === 0;
}

console.log(test("Alien", "line")); // true
console.log(test("Hello", "hello")); // true
console.log(test("hello", "hey")); // false

I tried something leaning on the ments from others and came up with this. It basically uses a count variable each time a letter in the substring returns a positive index value, then checks whether the total count is equal to the length of the substring(the logic being that any letter that returns -1 doesn't exist and would not be counted). If the count is equal, then all the letters have passed the test, if not, it fails the test.

It works for reversed letters, repeated letters in a substring(i.e 'heell' as a substring would also pass the test with 'hello'.

function test(str, substring) {
    let str1 = str.toLowerCase();
    let str2 = substring.toLowerCase();
    let count = 0;
    let answer = false;

    for(let i of str2){
        if(str1.indexOf(i) >= 0) {
            count+=1;
        }
    }
    return str2.length == count ? answer = true : answer;
}

console.log(test("Alien", "line")); // true
console.log(test("Hello", "olleh")); // true
console.log(test("hello", "hey")); // false

本文标签: javascriptTest If String Contains All Characters That Make Up Another StringStack Overflow