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
4 Answers
Reset to default 4Use .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条)