Reputation: 65
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
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:
green apple
as you said in the comment)// 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
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
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
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