Check if string contains all characters of another string javascript

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

function scramble[world, seed] {
    var arr = new Array[256];
    var i = 0;
    
    for [i = 0; i < 256; i++] {
      arr[i] = 0;
    }
    
    for [i = 0; i < world.length; i++] {
      arr[world.charCodeAt[i]] += 1;
    }
    
    for [i = 0; i < seed.length; i++] {
      arr[seed.charCodeAt[i]] -= 1;
      if [arr[seed.charCodeAt[i]] < 0] {
        return false;
      }
    }
    
    return true;
}

console.log[scramble['rkqodlw','world']];
console.log["should be true"];

console.log[scramble['cedewaraaossoqqyt','codewars']];
console.log["should be true"];

console.log[scramble['katas','steak']];
console.log["should be false"];

console.log[scramble['scriptjava','javascript']];
console.log["should be true"];

console.log[scramble['scriptingjava','javascript']];
console.log["should be true"];

console.log[scramble['jscripts','javascript']]; 
console.log["should be false"];

console.log[scramble['aabbcamaomsccdd','commas']];
console.log["should be true"];

Pretty sure it's much faster. As for why, it's about complexity. First a loop of 256 iterations [so nothing], then a loop O[n], then another O[n] loop, where n is the length of either string.

Your code is O[n*n]: a loop on the string's length, then the .replace call which is also O[n].

Explanation of the code

Each letter is an ASCII character. ASCII characters have a number representation from 1 to 128 [in the code 256 to be safe].

So I create an array of 256 values, filling it with zeros. Then I count the letters in the first string: increasing the count for the corresponding letter by one. I get the number representation of the letter with .charCodeAt.

Then, for the second string, I decrease the count of each letter by 1 as I encounter the characters. If I end up with a negative number, it means there was more of said letter in the second string than in the first string, and I return false.

The end result is a much faster algorithm.

To be fair, anyone doing C or C++ would come up with this solution.

Another solution

Another solution, less efficient but still meeting the speed criterion I assume, using objects:

function scramble[world, seed] {
    var obj = {};
    var i = 0;

    for [i = 0; i < world.length; i++] {
      arr[world[i]] = [arr[world[i]] || 0] + 1;
    }

    for [i = 0; i < seed.length; i++] {
      arr[seed[i]] = [arr[seed[i]] || 0 ] - 1;
      if [arr[seed[i]] < 0] {
        return false;
      }
    }

    return true;
}

It's another way of doing things even if you don't know the concept of number representation for letters.

Return true if the string in the first element of the array contains all of the letters of the string in the second element of the array.


console.log[stringContainString[["Alien", "line"]]];    // true
console.log[stringContainString[["zyxwvutsrqponmlkjihgfedcba", "qrstu"]]];    // true
console.log[stringContainString[["Hello", "hey"]]];    // false

function stringContainString[arr] {
  return arr[1].toLowerCase[]
    .split['']
    .every[function[letter] {
      return arr[0].toLowerCase[]
        .indexOf[letter] != -1;
    }];
}

Examples

Check if a string includes "world":

let text = "Hello world, welcome to the universe.";
let result = text.includes["world"];

Try it Yourself »

let text = "Hello World, welcome to the universe.";
let result = text.includes["world", 12];

Try it Yourself »

More examples below.

Definition and Usage

The includes[] method returns true if a string contains a specified string.

Otherwise it returns false.

The includes[] method is case sensitive.

Syntax

string.includes[searchvalue, start]

Parameters

Parameter Description
searchvalue Required.
The string to search for.
start Optional.
The position to start from.
Default value is 0.

Return Value

Type Description
A boolean. true if the string contains the value, otherwise false.

More Examples

Start at position 12:

let text = "Hello world, welcome to the universe.";
let result = text.includes["world", 12];

Try it Yourself »

Browser Support

includes[] is an ECMAScript6 [ES6] feature.

ES6 [JavaScript 2015] is supported in all modern browsers:

Chrome Edge Firefox Safari Opera
Yes Yes Yes Yes Yes

includes[] is not supported in Internet Explorer 11 [or earlier].


How do you check if a string has all characters of another string?

You can use contains[], indexOf[] and lastIndexOf[] method to check if one String contains another String in Java or not. If a String contains another String then it's known as a substring. The indexOf[] method accepts a String and returns the starting position of the string if it exists, otherwise, it will return -1.

How do you check if a string is present in another string in JavaScript?

Definition and Usage. The includes[] method returns true if a string contains a specified string. Otherwise it returns false .

How do you check whether a string contains all alphabets in JavaScript?

JavaScript: HTML Form validation - checking for all letters.
Javascript function to check for all letters in a field function allLetter[inputtxt] { var letters = /^[A-Za-z]+$/; if[inputtxt.value.match[letters]] { return true; } else { alert["message"]; return false; } } ... .
Flowchart:.
HTML Code

How do you check if a string only contains certain characters in JS?

Use the test[] method to check if a string contains only letters, e.g. /^[a-zA-Z]+$/. test[str] . The test method will return true if the string contains only letters and false otherwise.

Chủ Đề