Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

Just to illustrate what I want to do I'll pase this sample code for example:

<html>
<head>
</head>
<body>
<script type="text/javascript">
function oc(a)
{
  var o = {};
  for(var i=0;i<a.length;i++)
  {
    o[a[i]]='';
  }
  return o;
}
if ( "Island" in oc(["Hello","Hello World","Have","Island"]) )
{
document.write("Yes");
}
</script>
</body>
</html> 

In this case I get Yes on my page, but if I change the condition like:

if ( "Isl" in oc(["Hello","Hello World","Have","Island"]) )

the function doesn't find match. What is the best way to perform such kind of check which will return true even if only part of the string match?

Thanks

Leron

share|improve this question
Javascript is not Python. I suggest you try to drop that "in" hack of yours... – missingno May 15 '12 at 17:42

4 Answers

up vote 3 down vote accepted

Use .indexOf():

var str = 'hello world'
if (str.indexOf('lo') >= 0) {
    alert('jippy');
}

indexOf() returns the position where the value is found. If there is no match it returns -1 so we need to check if the result is greater or equal to 0.

share|improve this answer
Here is a useful reference for String.indexOf(str) on MDN. – maerics May 15 '12 at 17:41
Thanks, very fast and very useful! – Leron May 15 '12 at 17:43
you could also use the String .match() method and check for true, but this is will run faster. – ZanderKruz May 15 '12 at 17:43
@maerics thank you. I was looking for some docs. – Wouter J May 15 '12 at 17:44
1  
if you need case insensitivity, you can use .toLowerCase() on str, e.g. if (str.toLowerCase().indexOf('lo')) {. – D. Strout May 15 '12 at 17:45

You can use .test method from regexes.

var pattern = /Isl/;
pattern.test("Island"); // true
pattern.test("asdf"); //false
share|improve this answer
Also a good one, thanks – Leron May 15 '12 at 17:45
var s = "helloo";
alert(s.indexOf("oo") != -1);

indexOf returns the position of the string in the other string. If not found, it will return -1.

https://developer.mozilla.org/en/Core%5FJavaScript%5F1.5%5FReference/Objects/String/indexOf

share|improve this answer
<html> 
<head> 
</head> 
<body> 
<script type="text/javascript"> 
function inArray(str, array) 
{ 
  for(var i=0; i<array.length; i++) 
  { 
    if (array[i].indexOf(str) >= 0)
        return true;
  } 
  return false;
} 
if ( inArray("Island", ["Hello","Hello World","Have","Island"] ) 
{ 
document.write("Yes"); 
} 
</script> 
</body> 
</html> 
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.