So I have a textarea with content, only numbers and | (separators). Example :
<textarea>32|11|5|54|</textarea>
What I'd like is to append the textarea content, delete only the separators (the |) and keep the numbers, in their order. Get that kind of array :
var myArray = [22,9,54,37];
Note that I'm only allowed to basic JS
I know how to get the textarea content in a string, but I don't see how can I push() all the elements in an array, without breaking the numbers (ie having 2,2,9,5,4,3,7 instead of 22,9,54,37) AND deleting the separators. If needed I can change the separator, that's not a problem.
Pre-thanks.
4 Answers 4
Use
splitto split the string based on theseparator.
Use .filter to remove empty values
Use .map to cast string to Number
Try this:
var val = document.getElementById('ta').value;
var arr = val.split('|').filter(function(item) {
return item; //empty string is falsey value
}).map(Number); // cast string to Number
console.log(arr);
<script src="http://gh-canon.github.io/stack-snippet-console/console.min.js"></script>
<textarea id='ta'>32|11|5|54|</textarea>
4 Comments
32|11| |5|54|val.split('|').filter(String).map(Number)?String.trim instead, to address the above issue: val.split('|').filter(String.trim).map(Number)val.split('|').filter(String.trim).filter(isFinite).map(Number) to remove anything that's NaN. Glad to help :)You could use the split() function in javascript, and pass it the | as a parameter. This will create an array that contains all the numbers in order, without the | symbol.
If you need the numbers in order, then you can use the .join() with , passed in to create a string for output.
Javascript:
var textarea = document.getElementById( "textarea" ).value;
var values = textarea.split('|');
var valuesAsString = values.join(', ');
HTML:
<textarea id="textarea">32|11|5|14</textarea>
1 Comment
use trim in filter condition to check empty values.
try this
var res = '32|11|5|54|'.split('|').filter(function(v) {
return v.trim() != ''
})
document.write('<pre>' + JSON.stringify(res, 0, 4) + '</pre>')
res = '32|11||5|54|'.split('|').filter(function(v) {
return v.trim() != ''
})
document.write('<pre>' + JSON.stringify(res, 0, 4) + '</pre>')
res = '32|11| |5|54|'.split('|').filter(function(v) {
return v.trim() != ''
})
document.write('<pre>' + JSON.stringify(res, 0, 4) + '</pre>')
Comments
You're looking for the String.prototype.split method which accepts separator as an argument. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split
So in your case it will be '22|33|44'.split('|')
If you want add these values to an existing array, you should use Array.prototype.conat method: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/concat
new Array('2|11|5|54'.split(/\|/))