在JavaScript中使用RegEx从字符串中删除一个子字符串

时间:2012-06-05 15:21:10

标签: javascript regex

  

可能重复:
  how to replace last occurence of a word in javascript?

我有一个字符串,例如:“ 345 ,456,678, 345 345 ,678343,232”

我需要从字符串中删除最后一次出现 345 (在此示例中间,但可以在字符串中的任何位置)。考虑使用RegEx但无法找到正确的模式,无法在任何地方找到解决方案。

任何人都可以帮忙吗?

P.S。我知道我可以使用JavaScript字符串操作,但我认为这就是RegEx for ...

谢谢...... 埃雷兹

2 个答案:

答案 0 :(得分:3)

你可以这样做......

var str = "345,456,678,345,345,678,343,232",
    last_idx = str.lastIndexOf(345);

str = str.replace(/345/g, function(s, i) { return i === last_idx ? '' : s; });

正如@Crayon Violent所指出的,如果整合变量,应该从RegExp构造函数构建正则表达式。

function removeLast(str, v) {
    var re = new RegExp(v, 'g'),
        last_idx = str.lastIndexOf(v);

    return str.replace(re, function(s, i) { return i === last_idx ? '' : s; });
}

如果要删除的值是字符串的正则表达式,并且它应该用于lastIndexOf,那么您可以使用.exec()代替。

function removeLast(str, v) {
    var re = new RegExp(v, 'g'),
        match,
        last_idx;

    while (match = re.exec(str))
        last_idx = re.lastIndex - match.length

    return str.replace(re, function(s, i) { return i === last_idx ? '' : s; });
}

但是如果你打算使用.exec(),你总是可以在循环中构建新的字符串。你只需要确保在循环完成后排除最后一个匹配。

答案 1 :(得分:2)

how to replace last occurrence of a word in javascript?的最高回答修改:

function removeLast(str, target) {
    return str.replace(new RegExp("(.*)"+target), "$1");
}

这使用.*的贪婪 - 它会尝试尽可能多地获取字符串,包括所需目标的实例,直到它到达目标的最后一个实例。因此,整个正则表达式匹配整个字符串,包括最后一个bigt实例,然后用匹配的(.*)替换它,这是目标字符串之前的所有内容。