Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get biggest number in textarea?

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?

like image 335
stack Avatar asked Jan 20 '16 23:01

stack


2 Answers

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);
like image 149
MinusFour Avatar answered Nov 03 '22 01:11

MinusFour


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.

like image 33
Brett DeWoody Avatar answered Nov 02 '22 23:11

Brett DeWoody