clean()
Removes extraneous characters and leading zeros from RUT strings, returning a normalized version.
Basic Usage
import { clean } from 'rut.ts'
clean('12.345.678-5') // '123456785'
clean(' 12-345-678-5 ') // '123456785'
clean('00012345678K') // '12345678K'Type Signature
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 cleanoptions(optional) - Configuration optionsthrowOnError(boolean, default:true) - If false, returnsnullinstead of throwing
Return Value
- Default mode: Returns cleaned RUT string or throws error
- Safe mode: Returns cleaned RUT string or
nullif invalid
Examples
Basic Cleaning
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
import { clean } from 'rut.ts'
// Without safe mode (throws)
try {
clean('invalid')
} catch (error) {
console.error(error) // Error: String "invalid" is not valid as a 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 valid RUT
saveToDatabase(cleaned)
} else {
// Show error to user
showError('Invalid RUT format')
}
}What Gets Cleaned
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
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
Related Functions
format()- Add formatting to a clean RUTvalidate()- Validate a RUTdecompose()- Split into body and verifier
Last updated on