如何在textarea获得最大数量? [英] How to get biggest number in textarea?

查看:76
本文介绍了如何在textarea获得最大数量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的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>

现在我需要获得中最大的数字[] 。在这种情况下,我需要 3 。我怎么能这样做?

Now I need to get the biggest number which is in []. In this case I need to get 3. How can I do that?

推荐答案

你可以这样做:

var result = Math.max.apply(Math, textarea.value.match(/\d+/g).map(Number));

分手:

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

致电 Math.max 使用作为 Math 以及映射数组的参数。

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);

这篇关于如何在textarea获得最大数量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆