如何使用javascript查找和替换字符串中的2个整数

时间:2014-02-25 06:42:40

标签: javascript regex

我有一个字符串:“总时间:3小时15分钟”,文字可能不同,但它总是有2个整数,总是按小时和分钟的顺序。

然后我根据字段和其他值计算新的小时/分钟,因此我必须更新旧字符串。在javascript中匹配该字符串中的第一个和第二个整数并用新值替换它们的最佳方法是什么?

9 个答案:

答案 0 :(得分:2)

var str = 'Total time: 3 hours and 15 minutes';
var matches = str.match(/\d+/g);
var number1 = Number(matches[0]);
var number2 = Number(matches[1]);
str = str.replace(number1, '11').replace(number2, '22');
alert(str);

答案 1 :(得分:2)

尝试这样可以获得数小时和分钟

var pattern = /\d+/g;
var str = "Total time: 3 hours and 15 minutes";
var matches = str.match(pattern);
var hours = matches[0]; // will be 3
var minutes = matches[1]; // will be 15

答案 2 :(得分:0)

您可以创建一个函数来更新字符串,如下所示:

var generateStr = function(hour, minute) {
    return 'Total Time: ' + hour + ' hours and ' + minute + ' minutes'
}

答案 3 :(得分:0)

使用像这样捕获的正则表达式组:

var inputStr = 'Total time: 3 hours and 15 minutes';
var newHours = 4;
var newMinutes = 30;
var outputStr = inputStr.replace(/(^.*?)(\d+)(.*?)(\d+)/,
   '$1' + newHours + '$3' + newMinutes);

现在outputStr是'总时间:4小时30分钟'

修改

你也可以这样做:

var inputStr = 'Total time: 3 hours and 15 minutes';
var outputStr = inputStr.replace(/(^.*?)(\d+)(.*?)(\d+)/,
   function(match, p1, p2, p3, p4){
       p2 = parseInt(p2, 10) + 1;
       p4 = parseInt(p4, 10) + 10;
       return p1 + p2 + p3 + p4;
});

现在outputStr将是“总时间:4小时25分钟”

答案 4 :(得分:0)

此方法将保留原始字符串,允许编辑数字。

http://jsfiddle.net/cgVgq/

str = "Total time: 3 hours and 15 minutes";

//get all groups of numbers and non-numbers
var matches = str.match(/([\d]+|[^\d]+)/g);

//assumes there will be exactly two distinct numbers
matches[1] = parseFloat(matches[1]) + 42;
matches[3] = parseFloat(matches[3]) + 42;

//replace the string
str = matches.join("") //"Total time: 45 hours and 57 minutes"

答案 5 :(得分:0)

您可以尝试以下方法: -

var regex = /\d+/g;
var str = "Total time: 3 hours and 15 minutes";
var numbers = str.match(regex);
var hours = numbers[0]; 
var minutes = numbers[1]; 
alert(hours); 
alert(minutes);

答案 6 :(得分:0)

var s = "Total time: 3 hours and 15 minutes";
var r = /(.*?)(\d+)(.*?)(\d+)(.*?)/g;
var m = r.exec(s);
var hh = parseInt(m[2], 10);
var mm = parseInt(m[4], 10);
hh = hh + 1;
mm = mm + 1;
s = s.replace(r, "$1" + hh + "$3" + mm + "$5");

答案 7 :(得分:0)

什么是“最好的”?取决于你究竟在做什么以及如何定义“最佳”,太少的信息无法回答。

有很多方法可以实现这一目标。你不知道你曾尝试过什么,或者你有什么问题,你没有告诉我们。

但有些可能性。

的Javascript

var str = 'Total time: 3 hours and 15 minutes',
    arr = str.split(/(\d+)/),
    addHours = 5,
    addMinutes = 30,
    result,
    idx;

arr[1] = +(arr[1]) + addHours;
arr[3] = +(arr[3]) + addMinutes;
result = arr.join('');
console.log(result);

idx = 0;
result = str.replace(/(\d+)/g, function (match, p1, offset, string) {
    idx += 1;
    if (idx === 1) {
        return +(p1) + addHours;
    }

    return +(p1) + addMinutes;
});

console.log(result);

result = str.match(/^(.*?)(\d+)(.*?)(\d+)(.*?)$/).slice(1).reduce(function (acc, cur, index) {
    if (index === 1) {
        acc += +(cur) + addHours;
    } else if (index === 3) {
        acc += +(cur) + addMinutes;
    } else {
        acc += cur;
    }

    return acc;
}, '');

console.log(result);

jsFiddle

所有产生相同的结果。

答案 8 :(得分:0)

我会根据原始字符串创建一个可重用的函数:

<div id="time">Total time: 3 hours and 15 minutes</div>
var el = document.getElementById('time');
var refresh = new Function('return [' + (
    el.innerHTML.replace(/'/g, '\\\'').replace(
        /^(\D+)\d+(\D+)\d+(.+)$/, 
        '\'$1\',this[0],\'$2\',this[1],\'$3\''
    )
) + '].join(\'\');');

用法示例:

el.innerHTML = refresh.call([1, 2]); // "Total time: 1 hours and 2 minutes"
el.innerHTML = refresh.call([3, 4]); // "Total time: 3 hours and 4 minutes"

如果您不喜欢数组:

var refresh = new Function('return [' + (
    el.innerHTML.replace(/'/g, '\\\'').replace(
        /^(\D+)\d+(\D+)\d+(.+)$/, 
        '\'$1\',this.hours,\'$2\',this.minutes,\'$3\''
    )
) + '].join(\'\');');

用法示例:

el.innerHTML = refresh.call({ hours: 1, minutes: 2 });
el.innerHTML = refresh.call({ hours: 3, minutes: 4 });

如果你不喜欢.call()

var refresh = new Function('time', 'return [' + (
    el.innerHTML.replace(/'/g, '\\\'').replace(
        /^(\D+)\d+(\D+)\d+(.+)$/, 
        '\'$1\',time.hours,\'$2\',time.minutes,\'$3\''
    )
) + '].join(\'\');');

用法示例:

el.innerHTML = refresh({ hours: 1, minutes: 2 });
el.innerHTML = refresh({ hours: 3, minutes: 4 });

更进一步

演示:http://jsfiddle.net/wared/W4Xx8/

<div id="time">Total time: 3 hours and 15 minutes</div>
var refreshTime = function () {
    var el = document.getElementById('time');
    var tpl = new Function('return [' + (
        el.innerHTML.replace(/'/g, '\\\'').replace(
            /^(\D+)\d+(\D+)\d+(.+)$/, 
            '\'$1\',this.hours,\'$2\',this.minutes,\'$3\''
        )
    ) + '].join(\'\');');
    return function (data) {
        el.innerHTML = tpl.call(data);
    };
}();
refreshTime({ hours: 1, minutes: 2 });