npm install @ricardojrmcom/use-string-truncate
yarn add @ricardojrmcom/use-string-truncate
import { useStringTruncate } from '@ricardojrmcom/use-string-truncate';
/**
* Truncates string to fit within given length with appended ellipsis. Option to keep last word.
*/
export const TruncateString = ({
str,
length,
keepLastWord,
}: TruncateStringProps) => (
<span>
{useStringTruncate(str, length, keepLastWord)}
</span>
);
<TruncateString str="Lorem ipsum dolor sit amet" length={20} />
-> <span>Lorem ipsum dolor...</span>
<TruncateString str="Lorem ipsum dolor sit amet" length={20} keepLastWord />
-> <span>Lorem ipsum ... amet</span>
/**
* Exported TruncateString props
*/
export interface TruncateStringProps {
/**
* String to transform
*/
str: string;
/**
* Total length of the result
*/
length: number;
/**
* Option to keep last word in
*/
keepLastWord?: boolean;
}
MIT © Ricardo <l1b3r_-> Mota (@ricardojrmcom)
Bootstrapped with 🟣@ricardojrmcom/supernova