Skip to content

Instantly share code, notes, and snippets.

@OleksiyRudenko
Created March 16, 2026 20:10
Show Gist options
  • Select an option

  • Save OleksiyRudenko/c3dddb216c13386ea1a4d8be6902ab3d to your computer and use it in GitHub Desktop.

Select an option

Save OleksiyRudenko/c3dddb216c13386ea1a4d8be6902ab3d to your computer and use it in GitHub Desktop.
Shorten a long phrase & add ellipsis
($json.error.title ?? "")
//=== consider sanitizing whitespaces
//=== crop to intial 5 words
.replace(
/((\w+\s+){4}\w+)(\s.*)/, // find 5 words: 4 words followed by whitespaces + 1 word excluding the following space
"$1<=>$2") // demark the boundary with '<=>'
.split("<=>")
// remove empty entries (meaning there were no words to remove)
.filter(s=>s.length)
// replace non-empty tail with ""
.map((s,i)=>i?"":s)
// ellipsis will only be added if tail wasn't empty
.join("…")
//=== crop to initial 24 characters
.replace(
/(.{24})(.*)/, // find initial 24 characters and the tail
"$1<=>$2") // demark the boundary with '<=>'
.split("<=>")
// remove empty entries (meaning there were no words to remove)
.filter(s=>s.length)
// replace non-empty tail with "" so that ellipsis will be added
.map((s,i)=>i?"":s)
// ellipsis will only be added if tail wasn't empty
.join("…")
// The last .map().join() in each section can be replaced with `.map((s,i)=>i?"…":s)`
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment