I have a textarea like this:
<textarea>
this is a test [1] also this [2] is a test
and again [3] this is a test
</textarea>
Now I need to get the biggest number which is in []
. In this case I need to get 3
. How can I do that?
You could do:
var result = Math.max.apply(Math, textarea.value.match(/\d+/g).map(Number));
Breaking it up:
textarea.value.match(/\d+/g)
Gets you an array of numbers as strings.
.map(Number)
Maps each entry of the array from a string to a number.
Math.max.apply
Calls Math.max
with this
as Math
and as parameters the mapped array.
Edit: I didn't realize what you needed had to be in between brackets. You'll need to use a capture group for that and it's a little bit more complicated now.
var reg = /\[(\d+)\]/g, numberStrings = [ ], match;
while((match = reg.exec(textarea.value)) !== null){
numberStrings.push(match[1]);
}
var result = Math.max.apply(Math, numberStrings.map(Number));
It's a little bit more tricky to get the array of strings with the numbers.
Another alternative, without using a capture group:
var numbersInBrackets = textarea.value.match(/\[\d+\]/g);
var numbers = numbersInBrackets.map(function(x) {
return Number(x.substring(1, x.length - 1));
});
var result = Math.max.apply(Math, numbers);
Same idea as MinusFour's solution. Uses jQuery but could easily be done without.
var content = $('textarea').val();
var contentArr = content.split(' ');
var nums = [];
for (var i = 0; i < contentArr.length; i++) {
var txt = contentArr[i];
if (txt.match(/[\d]/)) {
nums.push(Number(txt.slice(1,-1)));
}
}
// Max number is Math.max.apply(null, nums)
Full working JSFiddle.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With