Remove all characters after last - but only if after - has four characters
I have a string which could contain several different values, among them are.
EDITED for clarity: var test could equal FW21002-185 or FW21002-181-0001 or abcdefg or 245-453-654 or FW21002-181-00012
I would like to remove all characters after and including the last - only if that string contains four characters after the last dash. So in the above strings examples, the only one that should be changed is the second one to "FW21002-181" All others would remain as they are开发者_如何学编程.
How would I do this in JavaScript. Regex is ok as well. Thanks.
A regex to do this would be
var chopped = test.replace(/-[^-]{4,}$/, '-');
(assuming you want that "-" at the end). (Oh also this is intended to match 4 or more trailing characters - if you want exactly four, just get rid of the comma in {4,}
.)
No regex required:
var str = ...,
pos = str.lastIndexOf('-');
if (pos > -1 && pos == str.length - 5)
str = str.substring(0, pos);
If you don't want to use a regex:
function removeLongSuffix(var str)
{
var tokens = str.split('-'),
last = tokens[tokens.length-1];
if (last.length > 3)
{
return tokens.slice(0,-1).join('-');
}
return str;
}
精彩评论