如何在javascript中替换最后一个单词? [英] how to replace last occurrence of a word in javascript?

查看:127
本文介绍了如何在javascript中替换最后一个单词?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如:

var str="<br>hi<br>hi";

替换最后一个(第二个)< br>

to replace the last(second) <br>,

更改为< br> hihi

我试过:

str.replace(/<br>(.*?)$/,\1);

但这是错误的。什么是正确的版本?

but it's wrong. What's the right version?

推荐答案

你可以使用量词贪婪的事实:

You can use the fact that quantifiers are greedy:

str.replace(/(.*)<br>/, "$1");

但缺点是它会导致回溯。

But the disadvantage is that it will cause backtracking.

另一个解决方案是拆分字符串,将最后两个元素放在一起然后加入部分:

Another solution would be to split up the string, put the last two elements together and then join the parts:

var parts = str.split("<br>");
if (parts.length > 1) {
    parts[parts.length - 2] += parts.pop();
}
str = parts.join("<br>");

这篇关于如何在javascript中替换最后一个单词?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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