2

How can I determine if a string contains one of the values from an array?

For example:

var a = ["abc","def","ghi"];

var s = "jskljfdkljflkjk abc jskfdjklsj";


for(var i=0;i<a.length;i++){
    if(/a[i]/.test(s)) alert(1);
}

This obviously doens't work... I know it's very possible though hahaha

2
  • Do you want to match stuff like "ABC" in "jskljfdABCkljflkjk"? Commented May 24, 2013 at 14:34
  • thanks everyone! looks like i have a few different methods to choose from :) Commented May 24, 2013 at 14:40

4 Answers 4

3

Your syntax for creating the regular expression is incorrect. That regex will only return true for a string "ai". And you're testing the regular expression against the array. I think what you meant to write is:

if(RegExp(a[i]).test(s)) alert(1);

You would probably be better off just using indexOf in this case. It'll be faster and you won't need to escape any characters.

var a = ["abc","def","ghi"],
    s = "jskljfdkljflkjk abc jskfdjklsj";

for(var i = 0, l = a.length; i < l; i++)
    if(s.indexOf(a[i])+1) alert('string s contains a value from array a');
Sign up to request clarification or add additional context in comments.

4 Comments

no need to create a host object with new here. Also, I think ~ has better perfs than +1 (will try)
Thanks! also great explanation too!!
@user1737909 you're right. I've removed the 'new' declaration from the regex.
@user1737909 seems like they are virtually the same in performance for all modern browsers ( test results )
1
function doesStringContainElementFromArray(str, arr)
{
  for ( var i=0; i<arr.length; i++)
  {
    if ( str.indexOf(arr[i]) != -1 )
      return true;
  }
  return false;
}

Comments

1

Just use the "RegExp" function/constructor (if you really need regexps)

if (RegExp(a[i]).test(a)) {
  alert(1);
}

if you don't, just use .indexOf

if (s.indexOf(a[i]) != -1) {
  alert("a[i]="+a[i]+" is matched in " + s);
}

3 Comments

Thanks! What if I don't need regex and just want to match strings?
yea thanks just realized as you answered. Mainly interested in your regex answer, but thanks alot!!
I think regexp is much slower than indexOf
1

You can use search method of JavaScript

var a = ["abc","def","ghi"];

var s  = "jskljfdkljflkjk abc jskfdjklsj";

for(var i=0;i<a.length;i++){

  if(s.search( a[i] ) != -1)
  {
     alert("found");
  }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.