Skip to content

clean()

Removes extraneous characters and leading zeros from RUT strings, returning a normalized version.

clean() is intentionally permissive: it normalizes input shape, but it does not validate the verifier digit. Use validate() before accepting a RUT in production flows.

Basic Usage#

TypeScript
import { clean } from 'rut.ts'
 
clean('12.345.678-5') // '123456785'
clean('  12-345-678-5  ') // '123456785'
clean('00012345678K') // '12345678K'

Type Signature#

TypeScript
function clean(rut: string): string
function clean(rut: string, options: { throwOnError: false }): string | null
function clean(rut: string, options: { throwOnError: true }): string
function clean(rut: string, options?: SafeOptions): string | null
 
type SafeOptions = {
  throwOnError?: boolean
}

Parameters#

  • rut (string) - The RUT string to clean
  • options (optional) - Configuration options
    • throwOnError (boolean, default: true) - If false, returns null instead of throwing

Return Value#

  • Default mode: Returns cleaned RUT string or throws error
  • Safe mode: Returns cleaned RUT string or null if invalid

Examples#

Basic Cleaning#

TypeScript
import { clean } from 'rut.ts'
 
// Remove dots and hyphens
clean('12.345.678-5') // '123456785'
 
// Remove spaces
clean(' 12 345 678 5 ') // '123456785'
 
// Remove leading zeros
clean('0012345678-5') // '123456785'
 
// Uppercase K
clean('12345678k') // '12345678K'

Safe Mode#

TypeScript
import { clean } from 'rut.ts'
 
// Without safe mode (throws)
try {
  clean('invalid')
} catch (error) {
  console.error(error) // Error: Invalid RUT input
}
 
// With safe mode (returns null)
const result = clean('invalid', { throwOnError: false })
console.log(result) // null
 
// Useful for form validation
const handleInput = (value: string) => {
  const cleaned = clean(value, { throwOnError: false })
  if (cleaned) {
    // Process normalized RUT shape, then validate before accepting it
    saveToDatabase(cleaned)
  } else {
    // Show error to user
    showError('Invalid RUT format')
  }
}

What Gets Cleaned#

TypeScript
import { clean } from 'rut.ts'
 
// Multiple hyphens
clean('12-345-678-5') // '123456785'
 
// Special characters
clean('12#345$678%5') // '123456785'
 
// Mixed formatting
clean('12.345-678 5') // '123456785'
 
// Parentheses
clean('(12.345.678-5)') // '123456785'
 
// Leading zeros (removed)
clean('000012345678-5') // '123456785'

Validation Rules#

The function validates:

  • ✅ Length must be 8-9 characters after cleaning
  • ✅ K (if present) must be at the end
  • ✅ Only one K allowed
  • ✅ Only digits and K allowed

It does not validate:

  • The Modulo 11 verifier digit
  • Whether the original input used canonical dot or hyphen grouping

Use Cases#

  • ✅ Normalize RUTs before database storage
  • ✅ Clean user input before validation
  • ✅ Prepare RUTs for API calls
  • ✅ Remove formatting for processing
  • ✅ Safe form handling with throwOnError: false