Splitting Arrays

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Andi B

    Splitting Arrays

    If I have an array set up like so to contain a small code, and the name of
    the person to whom the code relates, the values split by a comma:

    DMCName[0]="1SC,Andrea Pidgeon"

    and I want to be able to return the name when someone enters the code into a
    text box, is there a way to split the array and only return the name? -
    Bearing in mind that there will be more than one code, and other details
    will be included besides the name of the person, and that such a method of
    splitting would have to be able to scan through all (roughly 40 entries) in
    the array and compare the code to the users entry...


  • Grant Wagner

    #2
    Re: Splitting Arrays

    Andi B wrote:
    [color=blue]
    > If I have an array set up like so to contain a small code, and the name of
    > the person to whom the code relates, the values split by a comma:
    >
    > DMCName[0]="1SC,Andrea Pidgeon"
    >
    > and I want to be able to return the name when someone enters the code into a
    > text box, is there a way to split the array and only return the name? -
    > Bearing in mind that there will be more than one code, and other details
    > will be included besides the name of the person, and that such a method of
    > splitting would have to be able to scan through all (roughly 40 entries) in
    > the array and compare the code to the users entry...[/color]

    The split() method returns an array:

    var splitStuff = DMCName[0].split(/,/);
    var userInput = "whatever";

    for (var i = 0; i < splitStuff.leng th; i++) {
    if (splitStuff[i] == userInput) {
    // you found a match
    break;
    }
    }

    If you know the name is always the second thing in the string, you could also do
    something like:

    if (DMCName[0].split(/,/)[1] == userInput) {
    // found a match
    }

    --
    | Grant Wagner <gwagner@agrico reunited.com>

    * Client-side Javascript and Netscape 4 DOM Reference available at:
    *


    * Internet Explorer DOM Reference available at:
    *
    Gain technical skills through documentation and training, earn certifications and connect with the community


    * Netscape 6/7 DOM Reference available at:
    * http://www.mozilla.org/docs/dom/domref/
    * Tips for upgrading JavaScript for Netscape 7 / Mozilla
    * http://www.mozilla.org/docs/web-deve...upgrade_2.html


    Comment

    Working...