wiaK
wiaK

Reputation: 65

Textarea to filtred array Javascript

Im trying to take the value of textarea, split it into different properties.

Data in textfield(This is an example, there is alot more spaces in the real input):

    name       lastname        age             fruit
    john                doe             22             apple
eric                jonsson             23             apple

This Is my code right now:

        var textareadataData = $('#textareaID').val().split('\n');

Result:

"    name       lastname        age             fruit"
"    john                doe             22             apple"
"eric                jonsson             23             apple"

I want the result to be:

"name","lastname","age","fruit"
"john","doe","22";"apple"
"eric", "jonsson","23","apple"

I've tried to search around but didn't find the answer.

Best Regards Wiak

Upvotes: 2

Views: 164

Answers (4)

vahdet
vahdet

Reputation: 6729

You can use whitespace splitting after the one for new line.

The code below adds up your new-line-split with the operations:

  1. Filter out empty lines
  2. Split each line on multiple spaces (not to split green apple as you said in the comment)
  3. Gets rid of the empty/whitespace elements of the nested arrays

// This is your code
var textareaData = $('#textareaID').val().split('\n');

// This is the extra code you can add (split whitespaces and filter out resulting ones)
var words = textareaData
  .filter(x => x.length !== 0)
  .map(x => x.split(/(\s\s+)/))
  .map(x => x.filter(el => el.trim()));

console.log(words)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea id="textareaID">
    name       lastname        age             fruit
    john                doe             22       green apple
eric                jonsson             23             apple
</textarea>

Upvotes: 3

Marvin Fischer
Marvin Fischer

Reputation: 2572

You can use the following code:

$('#textareaID').val().split('\n').map(val => val.trim().replace(/[ ]+/g, " ").split(" "));

To explain the code:

$('#textareaID').val().split('\n') is your code

.map() iterates over all lines

val.trim() removes outer whitespaces

replace(/[ ]+/g, " ") removes all duplicated whitespaces

split(" ") splits everything

Upvotes: 0

Maxime Girou
Maxime Girou

Reputation: 1570

Please try

var string = $('#textareaID').val().replace(/\s+/g,' ')

The regex will replace all space by one space

then you can use split as usual

string.split(" ");

Upvotes: 0

Kashmir54
Kashmir54

Reputation: 135

Try to leave one space betwwen words with a regular expression:

var textData = textareadataData.replace(/\s+/g, " ");

Then split it again with the spaces:

var textDataArray = textData.split(" "); 

And there you have it. You can do it in just one line but I did it in two just to explain it.

Upvotes: 0

Related Questions