IdeaMonk

thoughts, ideas, code and other things...

Friday, June 27, 2008

instr is indexOf in javascript

Is there any equivalent of instr of VBscript in javascript, yes there is, its called indexOf
object.indexOf (string);

this will give you position of string in the object indexed from 0. examples -
var foo="ideamonk";
document.writeln (foo.indexOf("idea"));
document.writeln (foo.indexOf("monk"));
document.writeln (foo.indexOf("nothing"));

the output is likely to be -
0
4
-1

Labels:

6 Comments:

At November 11, 2008 at 5:37 PM , Anonymous Anonymous said...

Hey thanks, this was really useful.

 
At March 13, 2009 at 5:20 PM , Blogger KansasCoder said...

It looks like you are you mixing quotation marks around your search term. Is that right?

 
At March 13, 2009 at 5:48 PM , Blogger Abhishek Mishra said...

@Prairie: woops... thanks a lot... I've changed the code now. That really slipped my eyes...

# document.writeln (foo.indexOf('idea"));

becomes

# document.writeln (foo.indexOf("idea"));

 
At September 10, 2011 at 3:50 PM , Anonymous Anonymous said...

Cheers!

 
At October 3, 2011 at 1:59 AM , Blogger Weilun said...

Hey, I try to change
var foo="ideamonk";
to
var foo=document.getElementById('myText');
but it kills the script, why's that?

 
At October 3, 2011 at 1:55 PM , Blogger Abhishek Mishra said...

Here's what's happening, document.getElementById would return you a DOM node, if exists. Which would be of the type Object in javascript. Whereas indexOf, in javascript, exists in the prototype of String types. Which is why it wouldn't work for an object.

Now, I suppose you're trying to make indexOf work on contents of an element, whose id is known. If that's the case, you could try it this way -

var foo = document.getElementById('myText').innerHTML;

If you use jquery, things would be even more easier -

var foo = $("#myText").html();

 

Post a Comment

Subscribe to Post Comments [Atom]

<< Home