-3
所以我一直在研究這個函數,但我無法弄清楚如何去除字符串末尾的其餘連字符。Javascript:刪除連字符
function solution(s) {
var l = s.length,
max = l - (l % 3 ? ((l + 1) % 3 ? 4 : 2) : 0);
var result = "";
for(var i = 0; i < max; i+=3) {
result += s.replace(/[^0-9]/gi, '').slice(i, i + 3) + "-";
}
for(var i = max; i < l; i+=2) {
result += s.replace(/[^0-9]/gi, '').slice(i, i + 2) + "-";
}
return result.slice(0,-1);
}
console.log(solution("0 - 22 1985--324"));
console.log(solution("555372654"));
我知道「result.slice(0,-1)」應該已經解決了該問題,但它只是刪除在最後一個連字符。
預期產量是多少? – epascarello
您可以添加一個簡單的'輸入:'''預期輸出:'示例?目前還不清楚你想要做什麼。 –
Nope
你可以使用正則表達式來做到這一點:'result.replace(/ \ - $ /,'')' – elegisandi