Search code examples
javascriptnode.jsswig-template

Nodejs swig, substring or limit chars


Is there any way to limit string? Example:

{{item | limit(50)}}

Or maybe substring function?


Solution

  • There isn't exactly a filter that does that out of the box, but you can do it using replace.

    {{ item | replace("^(.{50,50})(.*)", "$1") }}
    

    This creates a RegExp that captures the first 50 characters ( any character: '.' between 50 and 50 times '{50,50}' ) then puts it in $1 and anything left goes in rest as $2. Then you replace the result with just $1... essentially throwing $2 away. It's a bit odd looking, but it will do the job.