javascript truncate string
var string = "ABCDEFG";
var truncString = string.substring(0, 3); //Only keep the first 3 characters
console.log(truncString); //output: "ABC"
javascript truncate string
var string = "ABCDEFG";
var truncString = string.substring(0, 3); //Only keep the first 3 characters
console.log(truncString); //output: "ABC"
Truncate a String
const truncateString = (str, num) => {
/******* Method One(1) *******/
// Return the actual string if num is equal or greater than str,
// else return the slice/copy the str from index 0 to index n(num), then truncate.
return num >= str.length ? str : str.slice(0, num)+'...'
/******* Method Two(2) *******/
let newString = ''
// Return same string if number length is greater or equal
if(num >= str.length) newString += str;
// Split each string, set new string to the spliced arr, join the new string and truncate
else newString += str.split('').splice(0, num).join('')+'...'
return newString
/******* Method Three(3) *******/
let truncateString = ''
// Optimize, to aviod looping through str when it is greater than the num
if(num >= str.length) {
truncateString = str
return truncateString
}
else for(let i = 0; i < num; i++) truncateString += str[i]
return truncateString+'...'
// OR
let truncateString = ''
for(let i = 0; i < num; i++) truncateString += str[i]
// Conditionally search to avoid result returning undefined for num greater than str length
return num >= str.length ? str : truncateString+'...'
}
truncateString("Peter Piper picked a peck of pickled peppers", 11);
Truncate a string
function truncateString(str, num) {
// Clear out that junk in your trunk
if (str.length > num) {
return str.slice(0, num) + "...";
} else {
return str;
}
}
string truncate
text_truncate = function(str, length, ending) {
if (length == null) {
length = 100;
}
if (ending == null) {
ending = '...';
}
if (str.length > length) {
return str.substring(0, length - ending.length) + ending;
} else {
return str;
}
};
console.log(text_truncate('We are doing JS string exercises.'))
console.log(text_truncate('We are doing JS string exercises.',19))
console.log(text_truncate('We are doing JS string exercises.',15,'!!'))
Truncate a string
function truncateString(str, num) {
if (str.length > num) {
return str.slice(0, num) + "...";
} else {
return str;
}
}
truncateString("Lorem Ipsum placeholder text in any number of characters, words sentences or paragraphs", 9) // returns Lorem Ips...
Copyright © 2021 Codeinu
Forgot your account's password or having trouble logging into your Account? Don't worry, we'll help you to get back your account. Enter your email address and we'll send you a recovery link to reset your password. If you are experiencing problems resetting your password contact us