Home > Software engineering >  Javascript slicing with 3 parameters
Javascript slicing with 3 parameters

Time:09-28

I am attempting to slice my text, in such a way that if the character lenght of a text exceeds the given value, the text should slice from 0 to the value also go until the next dot is found, so that we avoid slicing a text midsentence.

I've attempted the following

function shorten(text, num)
{
var fulltext=text.toString();
var firstdot = fulltext.indexOf("."); // Nu finder vi vores første punktum, så vi kan adskille sætningen
if (fulltext.length < num)
{
    return fulltext;
}
else
{
    return fulltext.slice(0, (num   fulltext.indexOf(".")));
}


}

So the logic is, if the text is below the given value, full text is returned, if not i want to slice the text, but also include the text, until next dot.

Example of what i want given lets say 10 as the num value. "Hello. This is a test example. This part should be removed."

Should return: "Hello. This is a test example." but instead it will return "Hello. This"

CodePudding user response:

Please change some code like this

function shorten(text, num)
{
    const fulltext=text.toString();
    const firstdot = fulltext.indexOf(".", num);
    return fulltext.length < num ? fulltext : fulltext.slice(0, firstdot   1);
}

console.log(shorten("Hello. This is a test example. This part should be removed.", 10));

CodePudding user response:

var str = "Hello. This is a test example. This part should be removed."
function shorten(text,num){
    let dot = text.indexOf(".",num)
    return text.slice(0,dot>=0?dot 1:num)
}
console.log(shorten(str,6))

  • Related