Sort lines by length
watermelon, fig, apple, pear and plum come back as fig, pear, plum, apple, watermelon: 3, 4, 4, 5 and 10 characters. pear stays ahead of plum because ties keep their original order. Free in your browser.
- Free
- Runs in your browser
- No sign-up
- Your data stays on your device
Run — free
Worked example
- Text
- watermelon fig apple pear plum
- Text
- fig pear plum apple watermelon
- Quantity
- 5
Sort lines by length when a list is easier to inspect, compare, or present with short entries first. Paste multiline text and this tool counts the Unicode characters in every line, orders the lines from shortest to longest, and preserves the original order whenever two lines have the same length. The result includes both copy-ready text and structured line records with their measured lengths, making it useful for quick manual cleanup and repeatable automated workflows.
How shortest-to-longest line sorting works
The tool treats every segment separated by a Windows CRLF pair, a line feed, or a carriage return as one line. It counts Unicode code points rather than JavaScript UTF-16 storage units, so a common emoji is counted as one character instead of two surrogate halves. It then compares the resulting character counts and places the smallest count first.
When two or more lines have the same count, their original relative order is retained. That stable tie rule matters for lists in which equal-length entries already have a meaningful sequence, and it makes repeated runs predictable. Blank lines are valid lines with a length of zero, including an empty segment created by a trailing line break, so they naturally move to the beginning.
Spaces and punctuation are characters and are not trimmed or rewritten. The returned text uses a single line-feed character between sorted lines, while the structured lines array pairs each original line value with its character length. No alphabetical tie-break is applied because this capability answers one clear question: how to sort lines by length from shortest to longest without silently changing equal-length ordering.
Preparing input and reading the result
Send an object with the required text field set to the complete multiline string. The value may contain one line, repeated lines, whitespace-only lines, non-Latin scripts, emoji, or mixed line-ending styles. On success, text is the copy-ready sorted block normalized to line-feed separators.
The lines array is designed for programs and contains objects with line and length fields, allowing a caller to display a table, verify a maximum width, or perform another transformation without counting again. Because the algorithm never trims content, a line containing three spaces has length three and remains distinguishable from a blank line. Combining marks are counted as separate Unicode code points, while surrogate-pair characters are counted once; this precise rule avoids platform-dependent visual-width guesses.
If the task instead requires terminal column width, locale-aware grapheme clusters, or alphabetical ordering, choose a tool built for that measurement or ordering rule rather than assuming all definitions of character width are interchangeable.
Using the sorter in lists, code, and tabular workflows
Length ordering is useful wherever unusually short or long lines reveal structure. Editors can arrange headings, labels, keywords, or product names so the compact entries appear first and awkward outliers become obvious at the bottom. Data teams can paste a single extracted column from a table and quickly see which records are likely empty, abbreviated, or unexpectedly verbose.
A practical automated flow can send exported labels, inspect the final line record for the greatest character count, and flag content that exceeds a downstream limit. Another can store the sorted text as a stable review artifact because equal-length lines keep their incoming order. The implementation performs no network request, uses no random source, and reads no clock, so the same input always returns the same output.
Remember that sorting changes row order: do not independently sort one column of a table when its neighboring columns must stay attached. In that case, sort complete records with an operation that preserves row relationships, or use this tool only after intentionally extracting a standalone list.
What you can do with it
Organize names and labels
Put short labels first while keeping labels of equal length in their original sequence.
Review code and configuration
Arrange snippets by character count so unusually long lines stand out at the end of the result.
Inspect extracted table values
Sort a standalone column to surface blank, abbreviated, and verbose entries without altering their content.
FAQ
What does the tool count as a character?
It counts Unicode code points. A typical surrogate-pair emoji counts as one character, while combining marks count separately.
How are lines with the same length ordered?
Their original relative order is preserved; no alphabetical tie-break is added.
Are spaces removed before measuring?
No. Leading spaces, trailing spaces, punctuation, and every other code point remain part of the line and its length.
What happens to blank lines?
Blank lines have length zero and therefore appear before non-empty lines. A trailing line break creates an empty final segment.
Can I sort from longest to shortest instead?
This tool always puts the shortest line first. For longest first, take the sorted result and reverse its line order; lines of equal length will then appear in the opposite of their original order.
Related tools
For developers — API access
Everything on this page is available programmatically. This section is for teams who want to wire it into their own systems; everyone else can just use the tool above.
API endpoint
Prefer to automate it? One authenticated POST creates the task; the result comes back by webhook or a signed link. The same capability also runs here on the web, by email and from Telegram — and soon from our app too.
Call it from your stack
curl -X POST https://api.kit.forhosting.com/str/sort-lines-length \
-H "Authorization: Bearer $KIT_KEY" \
-H "Content-Type: application/json" \
-d '{"text":"watermelon\nfig\napple\npear"}'const res = await fetch("https://api.kit.forhosting.com/str/sort-lines-length", {
method: "POST",
headers: {
"Authorization": `Bearer ${process.env.KIT_KEY}`,
"Content-Type": "application/json"
},
body: JSON.stringify({
"text": "watermelon\nfig\napple\npear"
})
});
const { task_id } = await res.json();import os, requests
res = requests.post(
"https://api.kit.forhosting.com/str/sort-lines-length",
headers={"Authorization": f"Bearer {os.environ['KIT_KEY']}"},
json={
"text": "watermelon\nfig\napple\npear"
},
)
task_id = res.json()["task_id"]<?php
$res = file_get_contents("https://api.kit.forhosting.com/str/sort-lines-length", false, stream_context_create([
"http" => [
"method" => "POST",
"header" => "Authorization: Bearer " . getenv("KIT_KEY") . "\r\nContent-Type: application/json",
"content" => '{"text":"watermelon\\nfig\\napple\\npear"}',
],
]));
$task = json_decode($res, true);body := bytes.NewBufferString(`{"text":"watermelon\nfig\napple\npear"}`)
req, _ := http.NewRequest("POST", "https://api.kit.forhosting.com/str/sort-lines-length", body)
req.Header.Set("Authorization", "Bearer "+os.Getenv("KIT_KEY"))
req.Header.Set("Content-Type", "application/json")
res, _ := http.DefaultClient.Do(req)Example request
{
"text": "watermelon\nfig\napple\npear"
}Example response
{
"task_id": "tsk_a1b2c3d4e5f6a1b2c3d4e5f6",
"type": "str.sort_lines_length",
"status": "queued",
"_links": {
"result": "/tasks/tsk_…/result"
}
}The API is asynchronous: the call returns a task_id immediately and the result arrives by webhook. Polling is capped at 1 req/s per task.
Pricing
Published price — no tokens, no invented credits. A failed task is never charged.
Errors
| HTTP | Code | Meaning |
|---|---|---|
401 | unauthorized | Missing or invalid API key. |
402 | insufficient_balance | Your balance doesn't cover the task price. |
404 | unknown_type | That task type doesn't exist. |
429 | rate_limited | Too many requests. Use the webhook instead of polling. |
Technical notes
Preparing input and reading the result
An empty string is still a valid piece of text and represents one empty line, but a missing text field or a non-string value is rejected as invalid_input. The count field reports how many line segments were processed, and method identifies the operation as sort_lines_length.
Using the sorter in lists, code, and tabular workflows
The browser tool is suitable for interactive work, while an API request costs $0.002 when the same deterministic operation belongs in a pipeline.
Technical questions
How much does the API operation cost?
Each successful API request costs $0.002. The browser version can run locally for interactive use.