Leron
Leron

Reputation: 9866

JavaScript - how can I check if a string is part or equal to another string

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

Upvotes: 0

Views: 5856

Answers (4)

Ron
Ron

Reputation: 1

<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> 

Upvotes: 0

hugomg
hugomg

Reputation: 69934

You can use .test method from regexes.

var pattern = /Isl/;
pattern.test("Island"); // true
pattern.test("asdf"); //false

Upvotes: 1

shareef
shareef

Reputation: 9581

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

Upvotes: 0

Wouter J
Wouter J

Reputation: 41934

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.

Upvotes: 4

Related Questions