删除除最后一次以外的所有事件 [英] Remove all occurrences except last?
问题描述
我想删除除最后一个字符串之外的字符串中出现的所有substring = 。
。
I want to remove all occurrences of substring = .
in a string except the last one.
EG :
1.2.3.4
应该成为:
123.4
推荐答案
2班轮:
function removeAllButLast(string, token) {
/* Requires STRING not contain TOKEN */
var parts = string.split(token);
return parts.slice(0,-1).join('') + token + parts.slice(-1)
}
不需要字符串参数的替代版本:
Alternative version without the requirement on the string argument:
function removeAllButLast(string, token) {
var parts = string.split(token);
if (parts[1]===undefined)
return string;
else
return parts.slice(0,-1).join('') + token + parts.slice(-1)
}
演示:
> removeAllButLast('a.b.c.d', '.')
"abc.d"
以下单行是一个正则表达式,利用 *
字符贪婪的事实,如果找不到匹配项,则替换将使字符串保持不变。它通过匹配[包括点的最长字符串] [点]并离开[字符串的其余部分]来工作,如果找到匹配,它将从中删除所有'。':
The following one-liner is a regular expression that takes advantage of the fact that the *
character is greedy, and that replace will leave the string alone if no match is found. It works by matching [longest string including dots][dot] and leaving [rest of string], and if a match is found it strips all '.'s from it:
'a.b.c.d'.replace(/(.*)\./, x => x.replace(/\./g,'')+'.')
(如果你的字符串包含换行符,则必须使用 [。 \ n]
而非裸体。
s)
(If your string contains newlines, you will have to use [.\n]
rather than naked .
s)
这篇关于删除除最后一次以外的所有事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!