创建一个函数来截断文本并在截断的文本末尾添加“...”。 JS
Create a function to truncate text and adding "..." at the end of the text truncated. JS
我是新手,正在学习 JS。
如标题中所述,如果他的长度高于最大长度,我希望浏览器 'alert' 文本被截断 +'...'。浏览器不这样做,有人可以帮我吗?
let str = prompt('Insert Text', '');
let maxLenght = +prompt('write max length', '');
function truncate(str, maxLenght) {
if (str.length > maxLenght) {
return str.slice(0, (maxLenght - 1)) + '...';
} else {
return str
}
}
alert(truncate());
您需要将变量传递给函数。此外,您不需要使用 maxLenght - 1
,因为 slice
默认情况下不包含最后一个索引。
let str = prompt('Insert Text', '');
let maxLenght = +prompt('write max length', '');
function truncate(str, maxLenght) {
if (str.length > maxLenght) {
return str.slice(0, (maxLenght)) + '...';
} else {
return str
}
}
alert(truncate(str, maxLenght));
我是新手,正在学习 JS。 如标题中所述,如果他的长度高于最大长度,我希望浏览器 'alert' 文本被截断 +'...'。浏览器不这样做,有人可以帮我吗?
let str = prompt('Insert Text', '');
let maxLenght = +prompt('write max length', '');
function truncate(str, maxLenght) {
if (str.length > maxLenght) {
return str.slice(0, (maxLenght - 1)) + '...';
} else {
return str
}
}
alert(truncate());
您需要将变量传递给函数。此外,您不需要使用 maxLenght - 1
,因为 slice
默认情况下不包含最后一个索引。
let str = prompt('Insert Text', '');
let maxLenght = +prompt('write max length', '');
function truncate(str, maxLenght) {
if (str.length > maxLenght) {
return str.slice(0, (maxLenght)) + '...';
} else {
return str
}
}
alert(truncate(str, maxLenght));