Closed Thread Icon

Preserved Topic: IndexOf problem Pages that link to <a href="https://ozoneasylum.com/backlink?for=18397" title="Pages that link to Preserved Topic: IndexOf problem" rel="nofollow" >Preserved Topic: IndexOf problem\

 
Author Thread
John H
Obsessive-Compulsive (I) Inmate

From: Preston, Lancashire, England
Insane since: May 2001

posted posted 04-09-2002 20:21

I'm having problems returning the index of a letter in a string correctly.

basically the script does 3 things:

1. has a list of letters from a - z in an array.

2. has a message written in a string.

3. returns the index in letters array of a letter in the message string, assigning it to a variable as a number.

code:
letters = new Array('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z',' ');

message = "a sentence of sorts";

letter = message.substr(0,1);
lettersIndex = letters.join().indexOf(letter);



The lettersIndex contains a nul value for some reason where it should return 0

Dark
Neurotic (0) Inmate
Newly admitted
posted posted 04-10-2002 03:48

what i would do is this:
Create a string of all the chars and use indexOf on the letter you want.

Dark

mr.maX
Maniac (V) Mad Scientist

From: Belgrade, Serbia
Insane since: Sep 2000

posted posted 04-10-2002 19:05

John H, I have tested the code from above and it worked fine. BUT, it won't do what you want; join() function will create string from array elements, but they will be separated by commas and using indeOf() on that string will return number that won't corespond to the actual index in array. You have to strip all commas before using indexOf() function...
<SCRIPT TYPE="text/javascript" LANGUAGE="JavaScript">
<!-- ;

letters = new Array('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z',' ');
message = "a sentence of sorts";
letter = message.charAt(2);
lettersIndex = letters.join().replace(/,/g, "").indexOf(letter);

// -->
</SCRIPT>


stinx
Bipolar (III) Inmate

From: London, UK
Insane since: Apr 2002

posted posted 04-11-2002 17:18

You could just use join with an empty string seperator...
The default value for the seperator is a comma, but you can override it i.e. -

lettersIndex = letters.join('').indexOf(letter);

That way you'll get the string as you want.

stinx.


John H
Obsessive-Compulsive (I) Inmate

From: Preston, Lancashire, England
Insane since: May 2001

posted posted 04-12-2002 04:03

I went with the string idea (letters = "abcd...") and it's all sorted out now.

« BackwardsOnwards »

Show Forum Drop Down Menu