It is necessary to cut 40 characters + the closest space ...

eg:

The text is the best in the world - cropping

It was the only way

const productTitle = $('.li'); const limit = 40; productTitle.each((e, i) => { if (i.text.length > 40) { i.text = `${i.text.slice(0, limit)}...`; } }); 

    2 answers 2

    You need to use the method String.replace() with the replacement by a regular expression

     (^.{N}([^ ]+|\s))(.*) 

    and throwing out the second group

    • ^.{N} - take N any ( . ) Characters from the beginning of the line ( ^ ). Where N is one less than the required number
    • ([^ ]+|\s) - then one or more non-whitespace characters or a space should go
    • (.*) - and then anything can go

     const productTitle = 'Текст лучший самый на свете'; const limit = 10; const re = new RegExp("(^.{" + (limit - 1) + "}([^ ]+|\\s))(.*)"); const cut = productTitle.replace(re, '$1'); console.log(cut); 

    Or without a constant limit

     const productTitle = 'Текст лучший самый на свете'; const cut = productTitle.replace(/(^.{9}([^ ]+|\s))(.*)/, '$1'); console.log(cut); 

    • Try instead of 10 numbers 5 and 6 - Ilya Zelenko
    • @ IlyaZelenko Thanks for the clarification. Corrected regexp - Anton Shchyrov
    • Still prints in the first if you put 5 then one word, if 6 is the whole line. In the second, if 5 is one word, 6 - 2 words. - Ilya Zelenko
    • Thank you so much!) - David Gabaraev
    • @ IlyaZelenko I forgot to screen the first one `. Если подставляете 6, то это означает, что нужно обрезать 7 и более. Так, что два слова законные. Я в пояснении написал, что число `. Если подставляете 6, то это означает, что нужно обрезать 7 и более. Так, что два слова законные. Я в пояснении написал, что число `. Если подставляете 6, то это означает, что нужно обрезать 7 и более. Так, что два слова законные. Я в пояснении написал, что число N - 1` - Anton Shchyrov

     const text = 'Текст лучший самый на свете после пробела' // обрезает до сюда(включительно) ^ console.log(get(text)) function get (text, limit = 30) { const slice = text.slice(0, limit) // лучший в мире способ определить пробелы const rightWhitespace = /[\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF]*$/ return slice.replace(rightWhitespace, '') + '...' } x0A \ x0B \ x0C \ x0D \ x20 \ xA0 \ u1680 \ u180E \ u2000 \ u2001 \ u2002 \ u2003 \ u2004 \ u2005 \ u2006 \ u2007 \ u2008 \ u2009 \ u200A \ u202F \ u205F \ const text = 'Текст лучший самый на свете после пробела' // обрезает до сюда(включительно) ^ console.log(get(text)) function get (text, limit = 30) { const slice = text.slice(0, limit) // лучший в мире способ определить пробелы const rightWhitespace = /[\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF]*$/ return slice.replace(rightWhitespace, '') + '...' }