Text Processing in JavaScript

From the JavaScript Regular Expressions cheat sheet · Common Patterns · verified Jul 2026

Text Processing

Patterns for text manipulation

javascript
// Remove extra spaces
text.replace(/\s+/g, ' ').trim()

// Remove HTML tags
html.replace(/<[^>]*>/g, '')

// Extract URLs from text
text.match(/https?:\/\/[^\s]+/g)

// Convert camelCase to kebab-case
"camelCaseString".replace(/([A-Z])/g, '-$1').toLowerCase()
// "camel-case-string"

// Convert snake_case to camelCase
"snake_case_string".replace(/_([a-z])/g, (_, letter) => letter.toUpperCase())
// "snakeCaseString"

// Find all hashtags
text.match(/#\w+/g)

// Find all mentions
text.match(/@[\w.]+/g)

// Extract numbers with units
"Height: 180cm, Weight: 75kg".match(/\d+(?:cm|kg|m|ft)/g)
// ["180cm", "75kg"]

// Remove duplicate words
text.replace(/\b(\w+)\s+\1\b/gi, '$1')

// Truncate to word boundary
text.substring(0, 100).replace(/\s\w+$/, '...')

// Convert markdown bold to HTML
text.replace(/\*\*(.+?)\*\*/g, '<strong>$1</strong>')
💡 Use non-greedy quantifiers for nested patterns
⚡ Remember to escape special characters when needed
📌 Test with edge cases like empty strings
🟢 Chain replace calls for multiple transformations
textprocessing

Continue with JavaScript Regular Expressions

Save the full cheat sheet or work through every related task.

More JavaScript tasks

Back to the full JavaScript Regular Expressions cheat sheet