Question

So What this is supposed to do, minus the mouseenter/mouseleave functions, is to take user input, divide it in to an array with 3 letters in each array placement (ex. User input abcdef... will turn in to abc, def,...). I read a different post on stack overflow, (How do you split a string at certain character numbers in javascript?). However, I can't quite get this to function in my following code.

Here is my script.js:

$(document).ready(function() {
    $('#button_translate').mouseenter(function() {
        $('#button_translate').fadeTo('fast', 1);
    });
    $('#button_translate').mouseleave(function() {
        $('#button_translate').fadeTo('fast', 0.7);
    });
    $('#button_clear').mouseenter(function() {
        $('#button_clear').fadeTo('fast', 1);
    });
    $('#button_clear').mouseleave(function() {
        $('#button_clear').fadeTo('fast', 0.7);
    });
    $('#button_translate').click(function() {
        var dna = $('input[name=dna]').val();
        var dna = dna.toUpperCase();
        function allBases(text) {  
            var bases = /^[ACGT]+$/;  
            if(text.match(bases)) {  

                var arr = Array.prototype.slice.call(dna), output = [];
                while (arr.length) output.push(arr.splice(0, 3).join('');
                document.write(arr + " is a DNA sequence.");

            }
            else
            {  
                document.write(dna + " is not a real DNA sequence.");
            }  
        }

        allBases(dna);

    });
});
Was it helpful?

Solution

I think this post might help:

Split string into array of equal length strings

Applying it to your code, you could replace:

    var arr = Array.prototype.slice.call(dna), output = [];
    while (arr.length) output.push(arr.splice(0, 3).join('');

with:

    var arr = text.match(/.{1,3}/g);

OTHER TIPS

Just change this

while (arr.length) output.push(arr.splice(0, 3).join('');

to this

while (arr.length) output.push(arr.splice(0, 3).join(''));

Notice the difference ? Missing ) at the end !!.

You don't need looping, you could use a regular expression. If I assume you want to treat all characters equally (spaces, number, punctuation) then:

var userString = 'I am a terrible swimmer';
var resultArray = userString.match(/[\s\S]{1,3}/g);

\s\S = anything. {1,3} = between 1 and three charaters. This will give you groups of three characters, and whatever is left over at the end (for if your string has, say, four characters in it).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top