0

I want save textarea lines in js array. this code works but if we have empty line in textarea, array elements values set undefined after empty line!
DEMO: http://jsfiddle.net/pYTjR/3/

<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
function check(){
var lines = $('#links').val().split(/\n/);
var texts = []
for (var i=0; i < lines.length; i++) {

  if (/\S/.test(lines[i])) {
    texts.push($.trim(lines[i]));
    }
var links = texts;
var str = links[i];
alert(i+"-  "+str);
}
}
</script>
</head>
<body>

<textarea id="links" name="upload" cols=80 rows=10>
www.example.com/book111.pdf
www.example.com/book222.pdf
www.example.com/book333.pdf

www.example.com/book444.pdf
www.example.com/book555.pdf
</textarea>

<input type="submit" id="getsize" name="getsize" value="textarea to array" onclick= "check()" />

</body>
</html>

DEMO: http://jsfiddle.net/pYTjR/3/

1 Answer 1

2

I think it is functioning as you are expecting except not alerting correctly. Try this:

http://jsfiddle.net/pYTjR/7/

function check(){
    var lines = $('#links').val().split(/\n/);
    var texts = [];
    for (var i=0; i < lines.length; i++) {
        if (/\S/.test(lines[i])) {
            texts.push($.trim(lines[i]));
        }
    }
    for (var i=0; i < texts.length; i++) {
        alert(i+"-  "+texts[i]);
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

How about spliting with multiple parameters, like comma and line?
Change the split parameter regex to include a comma

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.