Cleaning and reshaping text

Intermediate · 7 min

Trim, collapse whitespace, switch camelCase and snake_case, make slugs and strip control characters with one replace each, and know when a string method wins.

Before thisReplacing with regexLookaheadLookbehindUnicode property escapesCase folding, normalization and graphemesWriting patterns that run fast

CodeLucky · 7 min

Cleaning and reshaping text

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by CodeLuckyReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • String.trim() beats a regex for trimming. On x, 64,000 spaces, x the regex /^\s+|\s+$/g took 1,555 ms and trim() took 0.009 ms, because the trailing-space alternative is quadratic.
  • Collapse whitespace with s.replace(/\s+/g, ' ').trim(). One pass is possible with a replacer function, and in 20,000 random strings it agreed with the two-step version every time.
  • camelCase to snake_case needs more than ([a-z])([A-Z]) if you have acronyms. Splitting at positions with lookarounds gave parse_http_response and xml_http_request, where the simple rule gave parse_httpresponse.
  • A slug is four small steps: NFD-normalize, drop marks, lowercase, replace non-alphanumeric runs with a dash. ASCII-only slugs erase 日本語 and cut ß, so decide what you keep.
  • \p{Cc} removes control characters but not zero-width or direction marks. Add \p{Cf} for those, and keep \t and \n explicitly if you need them.

Messy input, one replace each

User input and scraped text arrive with stray spaces, odd casing and invisible characters. Cleaning it is the job where replace earns its keep: describe the junk, say what it becomes. I ran every pattern here in Node 26 and the Python ones in 3.9.

Trim and collapse

This string has leading spaces, a tab, a non-breaking space, newlines and a zero-width space:

const messy = "  \t Hello,  \n  world ​ ! \r\n ";
messy.replace(/\s+/g, " ").trim()   // "Hello, world ​ !"

\s+ matched every run of whitespace, including the non-breaking space U+00A0 and the byte-order mark U+FEFF (I checked both), and replaced each run with one space. It did not match the zero-width space U+200B, which is why one is still sitting between world and !, invisible. Whitespace in regex is not “everything that looks blank”.

Use String.prototype.trim() for trimming, not a regex. I trimmed "x" plus 64,000 spaces plus "x" both ways:

/^\s+|\s+$/g   1555 ms
String.trim()  0.009 ms

Same output, but the regex’s trailing-space branch retries at every space in the run, the quadratic pattern behind the Stack Overflow outage in the ReDoS lesson. Python’s equivalent is re.sub(r'\s+', ' ', s).strip(), which gave 'Hello, world' on my test.

If you want trim and collapse in one pass, a replacer function can decide per match:

const one = s => s.replace(/^\s+|\s+$|(\s)\s+|(\s)/g, (m, run, single) => run || single ? " " : "");

Leading and trailing runs become empty, inner runs become one space. I compared it against s.replace(/\s+/g, " ").trim() on 20,000 random strings of letters and whitespace and they never differed. It is also harder to read. Take the two-step version unless you have a reason.

camelCase and snake_case

The first attempt: put an underscore between a lowercase letter or digit and an uppercase letter, then lowercase everything.

s.replace(/([a-z\d])([A-Z])/g, "$1_$2").toLowerCase()

It handled userName (user_name) and html5Parser (html5_parser). It broke on acronyms:

parseHTTPResponse   simple: parse_httpresponse   better: parse_http_response
XMLHttpRequest      simple: xmlhttp_request      better: xml_http_request

The better version also splits where one capital is followed by a capital-then-lowercase pair, which marks the start of a new word. With lookarounds you split at positions and insert the underscore there:

s.replace(/(?<=[a-z\d])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])/g, "_").toLowerCase()

Python 3.9’s re.sub(r'(?<=[a-z0-9])(?=[A-Z])', '_', 'parseHttpResponse') split at the empty positions the same way and gave parse_http_response after .lower(). The reverse is a replacer function: s.replace(/_([a-z\d])/g, (_, c) => c.toUpperCase()) turned user_name into userName and parse_http_response into parseHttpResponse. Edge cases tell you to decide first: _private became Private and a__b became a_B.

Slugs

A URL slug is lowercase words joined by dashes. Four small steps do it:

const slug = s => s.normalize("NFD").replace(/\p{M}/gu, "").toLowerCase()
  .replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");

Normalizing to NFD splits è into e plus a mark, the mark is dropped, anything that is not a letter or digit becomes a dash run, and edge dashes go. Results:

"  Crème Brûlée & Co.!  "   creme-brulee-co
"C++ vs. C#"                c-vs-c
"Straße 42"                 stra-e-42
"日本語のタイトル"             ""

C++ and C# collapsed into the same slug, ß has no decomposition so it was lost and left a gap, and the Japanese title vanished completely. Swapping the class to [^\p{L}\p{N}]+ with the u flag kept straße-42 and 日本語のタイトル. Whether a slug may contain non-ASCII letters is a policy decision about your URLs; the regex just implements it. Always handle the empty result, for example by falling back to an ID.

Control characters

Invisible characters cause the worst bugs. I built "a\u0000b\u0007c\td\ne\u007ff​g‮h" and tried three removals:

/\p{Cc}/gu              "abcdef​g‮h"     controls gone, tab and newline too, U+200B and U+202E remain
/[^\P{Cc}\t\n]/gu       "abc\td\nef​g‮h"  keeps \t and \n
/[\p{Cc}\p{Cf}]/gu      "abcdefgh"        controls and format characters
/[\x00-\x1f]/g          "abcdef​g‮h"      old style misses U+007F and U+0085

\p{Cc} is the control category. U+200B (zero-width space) and U+202E (right-to-left override) are in Cf, format characters, and survive unless you add that. The double negative [^\P{Cc}\t\n] reads “a control character that is not tab or newline”. \p{Cc} matched U+0085 where [\x00-\x1f] did not. Removing Cf also removes the zero-width joiner U+200D: I stripped it from the family emoji 👨‍👩‍👧 and got three separate emoji, 👨👩👧. Use it on identifiers and filenames, not on free text.

About the video

“Regex Text Case Conversion: Title Case, camelCase, snake_case & kebab-case in Python” by CodeLucky was published 7 September 2025 and runs 6 minutes 34 seconds. The description says it converts text to title case, camelCase, snake_case and kebab-case with Python’s re module using patterns and replacement functions, and ends with a combined converter. The chapters follow that order. I couldn’t read a transcript, so I can’t judge whether it handles acronyms, which my own runs showed is where the simple rule breaks. It is in Python and my examples are mostly JavaScript, and it does not cover trimming, slugs or control characters. I have not watched other videos from this channel. The Excel video I first chose for the replacement mechanics is in the deeper links. English per its title and description.

What I did not run

Excel’s REGEXREPLACE itself, locale-specific case mapping, transliteration of non-Latin scripts to ASCII, and the replacement-pattern syntax of other flavours (\1, $&). I did not benchmark the camel-case or slug patterns.

Next

Cleaning assumes the text has a shape. Some text does not, and the next lesson is about recognizing it: when not to use a regex.

Check yourself

  1. 01Why is s.trim() preferable to s.replace(/^\s+|\s+$/g, '')?

    Both give the same result, but the regex retries \s+$ at every space in a long run and went quadratic: 1,555 ms against 0.009 ms on a 64,000-space string. trim() also reads more clearly.

  2. 02Why does the simple camel-to-snake rule turn parseHTTPResponse into parse_httpresponse?

    Rule ([a-z\d])([A-Z]) only inserts an underscore between a lowercase letter or digit and an uppercase letter. HTTPResponse is all capitals followed by a capital plus lowercase, so no boundary is found inside it. A second case, an uppercase letter before an uppercase-lowercase pair, splits it.

  3. 03What does a slug function that only keeps [a-z0-9] do to the Japanese title 日本語のタイトル, and what is the fix?

    It returns an empty string, since none of those characters are in a-z or 0-9. Keep letters and digits in any script with [^\p{L}\p{N}]+ and the u flag, or fall back to an ID when the slug is empty.

  4. 04You strip control characters with /\p{Cc}/gu, but zero-width spaces survive. Why?

    U+200B is a format character, category Cf, not a control character. Use [\p{Cc}\p{Cf}] to remove both, and be aware that this also removes joiners that some scripts and emoji need.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark