如何用" foo"?
替换字符串中最后一次出现的变量(foo)?我试过了:
var re = new RegExp(".*" + (foo)));
var newText = currentText.replace(re, someThingElse);
答案 0 :(得分:2)
负向前瞻可行,但
也是如此newText = newText.replace(new RegExp("(.*)" + foo), "$1somethingElse");
答案 1 :(得分:1)
如果再次出现针
,请进行否定预测以使匹配失败function replaceLast(haystack, needle, replacement) {
// you may want to escape needle for the RegExp
var re = new RegExp(needle + '(?![\\s\\S]*?' + needle + ')');
return haystack.replace(re, replacement);
}
replaceLast('foobarfoo', 'foo', 'baz'); // "foobarbaz"
replaceLast('foobarfoo \n foobarfoo', 'foo', 'baz'); // "foobarfoo \n foobarbaz"
replaceLast('foo ', 'foo', 'baz'); // "baz "
此方法的优点是替换正是您所期望的,即您可以正常使用$1
,$2
等,并且类似地,如果您传入函数< / em>参数也将是您所期望的
replaceLast('bar foobar baz', '(b)(a)(r)', '$3$2$1'); // "bar foorab baz"