skip to Main Content

If I have a number of characters (either as a string or an array), does JavaScript have a function to tell me if any of those characters appear within a string?

For example, given the following, I want a function that returns true because str does contain one of the characters in chars.

const chars = [ '[', ']', '{', '}' ];
var str = "BlahBlah}";

In C#, I can use IndexOfAny(), but I’m not finding a similar function in JavaScript.

4

Answers


  1. Try this

    const chars = [ '[', ']', '{', '}' ];
    const str = "BlahBlah}";
    
    const result = chars.some(x=>str.includes(x))
    
    console.log(result)
    Login or Signup to reply.
  2. JS contains metod includes. For example:

    const chars = [ '[', ']', '{', '}' ];
    var str = "BlahBlah}";
    
    for (const i of str) {
      if (chars.includes(i)) {
        console.log(i);
      }
    }
    
    Login or Signup to reply.
  3. ES6 automates looping through arrays with Array.prototype.some().

    Try:

    substrings.some(function(v) { return str.indexOf(v) >= 0; })
    

    Or, to prototype this to String yourself (not recommend):

    String.prototype.indexOfAny = function(arr) {
        return arr.some(function(v) { return str.indexOf(v) >= 0; });
    }
    
    Login or Signup to reply.
  4. Reusable Functional Approach

    const chars = [ '[', ']', '{', '}' ];
    const str = "BlahBlah}";
    
    const chars2 = [ '[', ']', '{', '}' ];
    const str2 = "Amoos";
    
    
    const findStringInArray = (string, array) => array.some( arr =>string.includes(arr) )
    
    
    console.log( findStringInArray(str, chars) )
    
    
    
    console.log( findStringInArray(str2, chars2) )
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search