Determine if string has at least 2 same elements from an array

Viewed 491

I want to determine if string has at least 2 same elements from the array

const array = ["!", "?"];

const string1 = "!hello"; // should return false
const string2 = "!hello?"; // should return false
const string3 = "!hello!"; // should return true
const string4 = "hello ??"; // should return true
const string5 = "hello ?test? foo"; // should return true
const string6 = "hello ?test ?? foo"; // should return true

I'm not sure what is gonna be better: a regex or a function? Any would be fine.

I tried this:

const array = ["!", "?"];
const string = "test!";

array.every(ar => !string.includes(ar));

But it only detects if there at least 1 elements from array, not 2.

9 Answers

You can use Array#some and String#split to do it:

const check=(array,string)=>array.some(char=>(string.split(char).length-1)>=2)

const array = ["!", "?"];

console.log(check(array,"!hello"))
console.log(check(array,"!hello?"))
console.log(check(array,"!hello!"))
console.log(check(array,"hello ??"))
console.log(check(array,"hello ?test? foo"))
console.log(check(array, "hello ?test ?? foo"))

How does it work?

Let's split up (I mean to split() up)!

const check=(array,string)=>
  array.some(char=>
    (
      string.split(char)
      .length-1
    )>=2
  )
  • First, use Array#some, which tests that at least one element of the array should pass (i.e. either ? or !)
  • Split up the string by char, and count how many parts do we have
    • If we have n parts, it means that we have n-1 places where the char matches. (e.g. 2 | splits a string into 3 parts: a|b|c)
  • Finally, test whether we have 2 or more delimiters

Another way is to use a pattern with a capturing group and a dynamically created character class for [!?] and a backreference \1 to what is captured in group 1 to make sure there are 2 of the same characters present.

([!?]).*\1

Regex demo

For example

const array = ["!", "?"];
const regex = new RegExp("([" + array.join(("")) + "]).*\\1");
[
  "!hello",
  "!hello?",
  "!hello!",
  "hello ??",
  "hello ?test? foo",
  "hello ?test ?? foo"
].forEach(str => console.log(str + ": " + regex.test(str)));

You can use string split and array length like:

const array = ["!", "?"];
const string6 = "hello ?test ?? foo"; 
var len1 = string6.split(array[0]).length;
var len2 = string6.split(array[1]).length;

if (len>2)||(len2>2)
 return true;

EDIT: Using for loop

for (let i=0;i<array.length;i++){
 var len = string6.split(array[i]).length;
 if (len>2)
  return true;
}
return false;

You can follow a very simple solution like below. Split the string using the character in array. check the left of the split operation. If the length is minimum 2, then return true, else false.

Here is a sample jsFiddle: https://jsfiddle.net/sagarag05/qk8f2Lz7/

const array = ["!", "?"];
var str = "How are you!! doing !today?";

function isFound(arr, str){
  var isPresent = false;
  for(var i=0; i < arr.length; i++){
      var res = str.split(arr[i]);
      if(res.length-1 >= 2){
          isPresent = true;
          break;
      }
  }
  return isPresent;
}
isFound(array, str);

Use loop over array and count occurrence then check if occurrence is greater than 1.

function has2(string1, array)
{
    for(let i=0;i<array.length;i++)
    {
        if (string1.split('').reduce(function(n, val) {
                return n + (val === array[i]);
            }, 0) > 1) 
        {
                return true;
        }
    }
    return false;
}

console.log(has2("!hello!", ["!", "?"])); // true
console.log(has2("!hello?", ["!", "?"])); // false

Here is a regex trick approach. We can try removing all characters from the input which are not part of the character class of characters to find. Then, assert that there are at least two distinct characters remaining in the input.

var input = "!hello?";
input = input.replace(/[^!?]+/g, "");
if (/(.).*(?!\1)./.test(input)) {
    console.log("MATCH");
}
else {
    console.log("NO MATCH");
}

The logic here is fairly straightforward. Using the input !hello? as an example, we first remove all non marker characters, leaving us with !?. Then, we use a regex to assert that there are at least two distinct characters remaining. This is true for this input, so we print MATCH.

Edit:

To build the regex alternation from your input array use join:

const array = ["!", "?"];
var regex = "[^" + array.join("") + "]+";

Create a function which can be handy for n number of occurrences to find

const arrayData = ["!", "?"];
const strData = "test!";

function checkElements(arr, str, occNum) {
   var ctr = 0;
   arr.forEach(function (elem) { if(str.includes(elem)) ctr++});

   return ctr >= occNum
}

checkElements(arrayData, strData, 2)

There is a much simpler solution for this:

var a = ["!", "?"], s = "!hello!";
a.some(v=>s.split(v).length>2) // (returns true if multiples are found)

We can turn it into a function to test:

const a = ["!", "?"];
function Test(s) { return a.some(v => s.split(v).length > 2) }
const string1 = "!hello"; // should return false
const string2 = "!hello?"; // should return false
const string3 = "!hello!"; // should return true
const string4 = "hello ??"; // should return true
const string5 = "hello ?test? foo"; // should return true
const string6 = "hello ?test ?? foo"; // should return true

console.log(Test(string1), Test(string2), Test(string3), Test(string4), 
  Test(string5), Test(string6));

> false false true true true true

Note: My code changed a few times and in the end was close to the accepted answer and I didn't realize. That said, you don't need to subtract anything, so that part is unnecessary.

function checkDups(arr, str) {
    var ctr = [];


    for (var i = 0; i < arr.length; i++) {
        var pos = str.indexOf(arr[i]);
        var count = 0;
        ctr[i] = 0;


        while (pos > -1) {
            ++count;
            pos = str.indexOf(arr[i], ++pos);
        }



        if (count >= 2) {
            return true
        }

    }


    return false
}

console.log(checkDups(["!", "?"], "!hello"))
console.log(checkDups(["!", "?"], "!hello?"))
console.log(checkDups(["!", "?"], "!hello!"))
console.log(checkDups(["!", "?"], "hello ??"))
console.log(checkDups(["!", "?"], "hello ?test? foo"))
console.log(checkDups(["!", "?"], "hello ?test ?? foo"))

Related