Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Postgres: limit length of returned string but needs to end on a full word

With Postgres I am trying to truncate a string before returning it so that I can display it in a partial results list client-side. The key is that it needs to end on a full word. I've gotten as far as: SELECT comments, substr(comments, 1, 80) AS "trunc" FROM book; Would the next step be to do a substring of the substring with RegEx (perhaps trying to make sure the string ends on a space)?

like image 567
eabates Avatar asked Oct 18 '25 08:10

eabates


1 Answers

Use substring(string from pattern). Example for 12 characters:

with the_data(comments) as (
    values
        ('follow me'::text),
        ('abcdef ghijkl'),
        ('abcd efgh ijkl'),
        ('abc def ghi jkl'),
        ('ab cd ef gh ij kl')
    )

select substring(left(comments || ' ', 12) from '.*\s')
from the_data;

  substring   
--------------
 follow me 
 abcdef 
 abcd efgh 
 abc def ghi 
 ab cd ef gh 
(5 rows)
like image 130
klin Avatar answered Oct 19 '25 23:10

klin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!