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

Just to illustrate what I want to do I'll pase this sample code for example:<html><head&

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

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 asked May 15, 2012 at 17:38 LeronLeron 9,90640 gold badges168 silver badges265 bronze badges 1
  • Javascript is not Python. I suggest you try to drop that "in" hack of yours... – hugomg Commented May 15, 2012 at 17:42
Add a ment  | 

4 Answers 4

Reset to default 4

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.

You can use .test method from regexes.

var pattern = /Isl/;
pattern.test("Island"); // true
pattern.test("asdf"); //false
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/en/Core%5FJavaScript%5F1.5%5FReference/Objects/String/indexOf

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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745142971a4613513.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信