Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 5 of 5
  1. #1
    New to the CF scene
    Join Date
    Nov 2013
    Location
    Iowa City, IA
    Posts
    2
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Extract a string into an array?

    How do you extract a string from a .js file into an array? I am stumped.

  • #2
    Regular Coder Vincent Puglia's Avatar
    Join Date
    Jul 2003
    Location
    where the World once stood
    Posts
    367
    Thanks
    0
    Thanked 13 Times in 13 Posts
    I presume your array is being declared within the html page, not that it really makes a difference. The only important thing to know is that the string needs to be declared before the array. Otherwise. you will get a null object error.

    <!DOCTYPE html>
    <html>
    <head>
    <script src="str.js"></script>
    <script>
    alert(myStr);
    var myArray = new Array();
    myArray[0] = myStr;
    alert(myArray[0])
    myArray[myArray.length++] = myStr;
    for (i = 0; i < myArray.length; i++)
    alert( " cell " + i + " contains " +myArray[i]);
    </script>
    <body>
    </body>
    </html>


    and in the str.js file:
    Code:
    var myStr = "This is my string";
    Where the world once stood
    the blades of grass
    cut me still

  • #3
    Senior Coder jmrker's Avatar
    Join Date
    Aug 2006
    Location
    FL
    Posts
    3,148
    Thanks
    39
    Thanked 506 Times in 500 Posts

    Arrow

    Alternate version. (external file inline for this example)
    Code:
    <!DOCTYPE html>
    <html>
    <head>
    <script>
    var myStr = "This is my string";  alert(myStr);
    var myArray = myStr.split(' ');   alert(myArray.join('\n'));
    var str = '';
    for (i = 0; i < myArray.length; i++) str += " cell " + i + " contains " +myArray[i] + '\n';
    alert(str);
    </script>
    <body>
    </body>
    </html>

  • #4
    New to the CF scene
    Join Date
    Nov 2013
    Location
    Iowa City, IA
    Posts
    2
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Thank-you guys both of these help a lot!

  • #5
    Regular Coder Vincent Puglia's Avatar
    Join Date
    Jul 2003
    Location
    where the World once stood
    Posts
    367
    Thanks
    0
    Thanked 13 Times in 13 Posts
    You're welcome
    Where the world once stood
    the blades of grass
    cut me still


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •