我正在尝试解决基本算法脚本问题:截断字符串;但不能正常工作...
let truncateString = (str, num) => {
return (str.length <= num ? str : str.slice(0, num > 3 ? num - 3 : num) + '...');
};
truncateString("A-tisket a-tasket A green and yellow basket", 8);
// running tests
truncateString("A-tisket a-tasket A green and yellow basket", 8) should return "A-tisket...".
truncateString("Peter Piper picked a peck of pickled peppers", 11) should return "Peter Piper...".
// tests completed
答案 0 :(得分:1)
比您的代码还要简单-稍微更改三元运算符:
let truncateString = (str, num) => str.length > num ? str.slice(0, num) + "..." : str;
console.log(truncateString("A-tisket a-tasket A green and yellow basket", 8));
console.log(truncateString("Peter Piper picked a peck of pickled peppers", 11));
答案 1 :(得分:0)
在这里:(有效)
let truncateString = (str, num) => {
return (str.length <= num ? str : str.slice(0, num) + '...');
};
答案 2 :(得分:0)
let truncateString = (str, num) => {
const x = str.length,
y = num,
min = y ^ ((x ^ y) & -(x < y));
return str.slice(0, min) + (!(y-min) && '...');
};