0

I have textarea and textare jsccode as the following :

var checkName = (document.getElementById("List").value);
var tempcheckNames = checkName.split('\n');

and assign array another array with trim.

for (var i = 0; i < tempcheckNames.length;i++){
    checkNames = tempcheckNames[i].trim().split('\n');
}

But checkNames is empty because assign with not array ?

So I want to trim from textarea value (I did textarea value split so my array is textarea value ('\n')

3
  • Should checkNames be a string, an array, or an array of arrays? Commented Jun 28, 2016 at 6:16
  • should be array @guest271314 Commented Jun 28, 2016 at 6:18
  • Just try checkName.split('\n').map(function(item){ return item.trim(); }) Commented Jun 28, 2016 at 6:20

3 Answers 3

1

This way, that's shorter

var checkName = document.getElementById("List").value.split("\n").map(element => element.trim());
Sign up to request clarification or add additional context in comments.

1 Comment

Yeap. that's it !!
1

Define checkNames as an array, use .push() to add items to checkNames array within for loop, remove call to .split() within for loop

for (var i = 0, checkNames = [] /* define `checkNames` as an array */
    ; i < tempcheckNames.length
    ; i++) {
    checkNames.push(tempcheckNames[i].trim()); 
    // .split('\n'); `.split()` not needed here
}

1 Comment

Thank you very much @guest271314
1

You can push the values to an array to get all the split values

var btn = document.getElementById('btn-show');
btn.addEventListener('click', btnShow);

function btnShow (e) {
  var checkName = (document.getElementById("list").value);
  var tempcheckNames = checkName.split('\n');
  var checkNames = [];
  
  for (var i = 0; i < tempcheckNames.length;i++){
    checkNames.push(tempcheckNames[i].trim());
  }
  alert(checkNames);
}
<textarea id='list'> </textarea>

<button id='btn-show'>Show</button>

Functional approach using Array.map

var btn = document.getElementById('btn-show');
btn.addEventListener('click', btnShow);

function btnShow (e) {
  var checkName = (document.getElementById("list").value);

  const checkNames = checkName.split('\n').map((name) => name.trim() );
  
  alert(checkNames);
}
    <textarea id='list'> </textarea>

    <button id='btn-show'>Show</button>

2 Comments

What is purpose of calling .split('\n') within for loop?
than you very much.

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.