Test If String Contains All Characters That Make Up Another String
Solution 1:
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.
Solution 2:
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);
}
Solution 3:
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
Solution 4:
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
Post a Comment for "Test If String Contains All Characters That Make Up Another String"