1

I have two strings:

var first = "913 DE 6D 3T 222"
var second = "913 DE 3T 222"

I want to check if second is present in first, preferably with regex. The problem is that indexOf or includes returns that second is not present in first, which is wrong (only 6D is the difference):

first.indexOf(second)
-1

first.includes(second)
false
user1665355
  • 3,324
  • 8
  • 44
  • 84

3 Answers3

3

Use String#split and Array#every methods.

var first = "913 DE 6D 3T 222";
var second = "913 DE 3T 222";

console.log(
  second
  // split the string by space
  .split(' ')
  // check all strings are contains in the first
  .every(function(v) {
    return first.indexOf(v) > -1;

    // if  you want exact word match then use regex with word
    // boundary although you need to escape any symbols which
    // have special meaning in regex but in your case I think all are 
    // alphanumeric char so which is not necessary

    // return (new RegExp('\\b' + v + '\\b')).test(first);
  })
)

FYI : For older browser check polyfill option of every method.


Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
1

This is a more elegant solution.

First of all, I'm using map function. In our case it is returning an array something like this:

[true,true,true,true]. Then, using reduce function and logical operators we will obtain one single value. If array containes at least one false value, then final result will be false.

var first = "913 DE 6D 3TT 222";
var second = "913 DE 3T 222";
console.log(second.split(' ').map(function(item){
    return first.includes(item);
}).reduce(function(curr,prev){
    return curr && prev;
}));
Mihai Alexandru-Ionut
  • 47,092
  • 13
  • 101
  • 128
0

The solution using String.match() function and a specific regex pattern:

I've change the first string to make a more complex case, duplicate DE value added.

var first = "913 DE 6D 3T 222 DE",
    second = "913 DE 3T 222",
    count = second.split(' ').length;

var contained = (count == first.match(new RegExp('(' + second.replace(/\s/g, "|") + ')(?!.*\\1)', "gi")).length);
console.log(contained);

(?!.*\1) - is negative lookahead assertion to avoid duplicate matches

RomanPerekhrest
  • 88,541
  • 4
  • 65
  • 105