我有一个句子,我希望只有最后的‘和’剩余,并删除其他。
“狮子,老虎,熊,大象”,我想把它变成:
狮子、老虎、熊和大象。
我尝试过使用regex模式,比如str = str.replace(/and([^and]*)$/, '$1');,它显然不起作用。谢谢。
发布于 2016-11-14 00:11:04
使用这个判据
and (?=.*and)and匹配任意一个,后面跟着一个空格。空间是匹配的,因此它在替换时被移除,以防止有两个空格。(?=.*and)是一种前瞻性,这意味着它只有在后面跟着.*and,如果后面跟着和使用以下代码:
str = str.replace(/and (?=.*and)/g, '');发布于 2016-11-14 00:10:21
您可以使用一个正面的前瞻性(?=...),以查看在当前匹配之前是否还有另一个and。您还需要使用g使regex全局化。
function removeAllButLastAnd(str) {
return str.replace(/and\s?(?=.*and)/g, '');
}
console.log(removeAllButLastAnd("Lions, and tigers, and bears, and elephants"));
发布于 2016-11-14 00:11:10
var multipleAnd = "Lions, and tigers, and bears, and elephants";
var lastAndIndex = multipleAnd.lastIndexOf(' and');
var onlyLastAnd = multipleAnd.substring(0, lastAndIndex).replace(/ and/gi, '')+multipleAnd.substring(lastAndIndex);
console.log(onlyLastAnd);https://stackoverflow.com/questions/40580193
复制相似问题