在字符串中使用英寸表示法提取数值并返回较大的数值

Extract numeric values with inch notation in a string and return larger one

本文关键字:返回 取数值 提取 字符串 表示      更新时间:2023-09-26

我正在尝试从具有类似名称的产品中提取尺寸信息。

Product A 30" Metalic Grey
Product B 31.50" Led 54 watt
Product C 40"-60" Dark Green

我当前获取尺寸信息的代码是

var product_name = $(this).text();
product_name.split('"')[0].slice(-2);

我很难处理点数,例如 31.50"。

有没有更好的方法可以从上面的示例产品名称中提取尺寸,也适用于产品名称,例如具有尺寸范围的第三个产品,它需要返回更大的数值,即 60。

如果要从字符串中获取所有大小,可以使用正则表达式['d.]+(?=")

var sizes = text.match(/['d.]+(?=")/g);

这将返回一个字符串数组,例如 ["31.50"]["40", "60"]

您可以进一步处理数组,例如将元素转换为数字:

sizes = sizes.map(Number); // ["31.50"] -> [31.50]

和/或获得最大值:

var maxSize = Math.max.apply(null, sizes); // ["40", "60"] -> 60

这个呢?

product_name.replace(/^.*?(['d'.]+)"[^"]*$/, '$1');
您需要在

第一个"符号处分开,然后找到它之前的最后一个空格:

var product_name = $(this).text();
var size = product_name.split('"')[0];
var space = product_name.lastIndexOf(' ');
size.slice(space, -1);

那会给你从"的一切,然后回到它之前的空间。

下面是一个示例,它将使用正则表达式来查找字符串,然后返回最大的字符串,遍历每个示例字符串:

var t = [
    'Product A 30" Metalic Grey',
    'Product B 31.50" Led 54 watt',
    'Product C 40"-60" Dark Green'
]
var getMaxInches = function(str) {
    var inches = str.match(/[0-9]+('.[0-9]+)?"/g); // The inches format pattern

    var maxMeasure = 0;
    for(i in inches){
        var measure =  (inches[i]).slice(0,-1); // remove the trailing "
        maxMeasure = Math.max(Number(measure),maxMeasure);
    }
    return maxMeasure;
}
for(var i in t) alert(getMaxInches(t[i]));