javascript 删除除最后一个之外的所有事件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9694930/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Remove all occurrences except last?
提问by lisovaccaro
I want to remove all occurrences of substring = .
in a string except the last one.
我想删除.
除最后一个之外的字符串中所有出现的 substring = 。
E.G:
例如:
1.2.3.4
should become:
应该变成:
123.4
采纳答案by ninjagecko
2-liner:
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)
}
Demo:
演示:
> 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,'')+'.')
(If your string contains newlines, you will have to use [.\n]
rather than naked .
s)
(如果你的字符串包含换行符,你将不得不使用[.\n]
而不是naked .
s)
回答by Сухой27
You can use regex with positive look ahead,
您可以使用正则表达式来积极展望,
"1.2.3.4".replace(/[.](?=.*[.])/g, "");
回答by icyrock.com
You can do something like this:
你可以这样做:
var str = '1.2.3.4';
var last = str.lastIndexOf('.');
var butLast = str.substring(0, last).replace(/\./g, '');
var res = butLast + str.substring(last);
Live example:
现场示例:
回答by Nina Scholz
You could take a positive lookahead (for keeping the last dot, if any) and replace the first coming dots.
您可以积极向前看(保留最后一个点,如果有的话)并替换第一个出现的点。
var string = '1.2.3.4';
console.log(string.replace(/\.(?=.*\.)/g, ''));
回答by kennebec
var s='1.2.3.4';
var s='1.2.3.4';
s=s.split('.');
s.splice(s.length-1,0,'.');
s.join('');
123.4
123.4
回答by danday74
A replaceAllButLast
function is more useful than a removeAllButLast
function. When you want to remove just replace with an empty string:
一个replaceAllButLast
功能是多了一个有用的removeAllButLast
功能。当您想删除时,只需用空字符串替换即可:
function replaceAllButLast(str, pOld, pNew) {
var parts = str.split(pOld)
if (parts.length === 1) return str
return parts.slice(0, -1).join(pNew) + pOld + parts.slice(-1)
}
var test = 'hello there hello there hello there'
test = replaceAllButLast(test, ' there', '')
console.log(test) // hello hello hello there
回答by danday74
Found a much better way of doing this. Here is replaceAllButLast
and appendAllButLast
as they should be done. The latter does a replace whilst preserving the original match. To remove, just replace with an empty string.
找到了一个更好的方法来做到这一点。这里是replaceAllButLast
和appendAllButLast
他们应该做的。后者在保留原始匹配的同时进行替换。要删除,只需替换为空字符串。
var str = "hello there hello there hello there"
function replaceAllButLast(str, regex, replace) {
var reg = new RegExp(regex, 'g')
return str.replace(reg, function(match, offset, str) {
var follow = str.slice(offset);
var isLast = follow.match(reg).length == 1;
return (isLast) ? match : replace
})
}
function appendAllButLast(str, regex, append) {
var reg = new RegExp(regex, 'g')
return str.replace(reg, function(match, offset, str) {
var follow = str.slice(offset);
var isLast = follow.match(reg).length == 1;
return (isLast) ? match : match + append
})
}
var replaced = replaceAllButLast(str, / there/, ' world')
console.log(replaced)
var appended = appendAllButLast(str, / there/, ' fred')
console.log(appended)
Thanks to @leaf for these masterpieces which he gave here.
感谢@leaf在这里提供了这些杰作。
回答by Marc
function formatString() {
var arr = ('1.2.3.4').split('.');
var arrLen = arr.length-1;
var outputString = '.' + arr[arrLen];
for (var i=arr.length-2; i >= 0; i--) {
outputString = arr[i]+outputString;
}
alert(outputString);
}
See it in action here: http://jsbin.com/izebay
在这里查看它的实际效果:http: //jsbin.com/izebay
回答by swapz83
You could reverse the string, remove all occurrences of substring except the first, and reverse it again to get what you want.
您可以反转字符串,删除除第一个之外的所有子字符串,然后再次反转它以获得您想要的。