Skip to content

trim

Removes whitespace from the beginning and end of a string.

Basic Usage

typescript
import { trim } from 'radash'

console.log(trim('  hello world  '))    // 'hello world'
console.log(trim('\t\nhello\n\t'))      // 'hello'
console.log(trim('hello'))              // 'hello'
console.log(trim('   '))                // ''

Syntax

typescript
function trim(str: string): string

Parameters

  • str (string): The string to process

Return Value

Returns the string with whitespace removed from the beginning and end.

Examples

Basic Whitespace Removal

typescript
import { trim } from 'radash'

console.log(trim('  hello world  '))    // 'hello world'
console.log(trim('hello world'))        // 'hello world'
console.log(trim('  hello  world  '))   // 'hello  world'
console.log(trim('hello'))              // 'hello'

Handling Different Types of Whitespace

typescript
import { trim } from 'radash'

// Spaces
console.log(trim('   hello   '))        // 'hello'

// Tabs
console.log(trim('\thello\t'))          // 'hello'

// Newlines
console.log(trim('\nhello\n'))          // 'hello'

// Carriage returns
console.log(trim('\rhello\r'))          // 'hello'

// Mixed whitespace
console.log(trim('\t\n hello \n\t'))    // 'hello'
console.log(trim(' \t\nhello\n\t '))    // 'hello'

Handling Edge Cases

typescript
import { trim } from 'radash'

// Empty string
console.log(trim(''))                   // ''

// Only whitespace
console.log(trim('   '))                // ''
console.log(trim('\t\n'))               // ''
console.log(trim(' \t\n '))             // ''

// No whitespace
console.log(trim('hello'))              // 'hello'
console.log(trim('hello world'))        // 'hello world'

Handling Special Characters

typescript
import { trim } from 'radash'

console.log(trim('  hello@world  '))    // 'hello@world'
console.log(trim('  hello#world  '))    // 'hello#world'
console.log(trim('  hello$world  '))    // 'hello$world'
console.log(trim('  hello%world  '))    // 'hello%world'
console.log(trim('  hello^world  '))    // 'hello^world'
console.log(trim('  hello&world  '))    // 'hello&world'

Handling Numbers and Symbols

typescript
import { trim } from 'radash'

console.log(trim('  123  '))            // '123'
console.log(trim('  3.14  '))           // '3.14'
console.log(trim('  -42  '))            // '-42'
console.log(trim('  +100  '))           // '+100'

Handling Chinese and Special Characters

typescript
import { trim } from 'radash'

console.log(trim('  你好世界  '))        // '你好世界'
console.log(trim('  Hello 世界  '))     // 'Hello 世界'
console.log(trim('  🌟hello🌟  '))      // '🌟hello🌟'
console.log(trim('  🎉🎊  '))           // '🎉🎊'

Handling HTML Content

typescript
import { trim } from 'radash'

console.log(trim('  <div>hello</div>  ')) // '<div>hello</div>'
console.log(trim('  <p>Hello World</p>  ')) // '<p>Hello World</p>'
console.log(trim('  <span>  content  </span>  ')) // '<span>  content  </span>'

Handling JSON Strings

typescript
import { trim } from 'radash'

const jsonStr = '  {"name": "Alice", "age": 25}  '
console.log(trim(jsonStr)) // '{"name": "Alice", "age": 25}'

const prettyJson = `
  {
    "name": "Alice",
    "age": 25
  }
`
console.log(trim(prettyJson)) // '{\n    "name": "Alice",\n    "age": 25\n  }'

Handling SQL Queries

typescript
import { trim } from 'radash'

const sqlQuery = `
  SELECT name, age
  FROM users
  WHERE age > 18
`
console.log(trim(sqlQuery)) // 'SELECT name, age\n  FROM users\n  WHERE age > 18'

Handling Configuration File Content

typescript
import { trim } from 'radash'

const configContent = `
  server:
    host: localhost
    port: 3000
  database:
    url: postgresql://localhost:5432/mydb
`
console.log(trim(configContent)) // 'server:\n    host: localhost\n    port: 3000\n  database:\n    url: postgresql://localhost:5432/mydb'

Handling User Input

typescript
import { trim } from 'radash'

function processUserInput(input: string) {
  const trimmed = trim(input)
  
  if (trimmed === '') {
    return 'Input cannot be empty'
  }
  
  return `Processed input: "${trimmed}"`
}

console.log(processUserInput('  hello world  ')) // 'Processed input: "hello world"'
console.log(processUserInput('   ')) // 'Input cannot be empty'
console.log(processUserInput('hello')) // 'Processed input: "hello"'

Handling Form Data

typescript
import { trim } from 'radash'

function validateFormData(data: Record<string, string>) {
  const errors: string[] = []
  const cleaned: Record<string, string> = {}
  
  for (const [key, value] of Object.entries(data)) {
    const trimmed = trim(value)
    cleaned[key] = trimmed
    
    if (trimmed === '') {
      errors.push(`${key} cannot be empty`)
    }
  }
  
  return { cleaned, errors }
}

const formData = {
  name: '  Alice  ',
  email: '  alice@example.com  ',
  phone: '   ',
  address: '  Beijing, China  '
}

const result = validateFormData(formData)
console.log(result)
// {
//   cleaned: {
//     name: 'Alice',
//     email: 'alice@example.com',
//     phone: '',
//     address: 'Beijing, China'
//   },
//   errors: ['phone cannot be empty']
// }

Handling API Responses

typescript
import { trim } from 'radash'

function processApiResponse(response: any) {
  return {
    message: trim(response.message || ''),
    data: response.data,
    status: response.status
  }
}

const apiResponse = {
  message: '  Success  ',
  data: { id: 1, name: 'Alice' },
  status: 200
}

const processed = processApiResponse(apiResponse)
console.log(processed) // { message: 'Success', data: { id: 1, name: 'Alice' }, status: 200 }

Handling File Content

typescript
import { trim } from 'radash'

function processFileContent(content: string) {
  const lines = content.split('\n')
  const trimmedLines = lines.map(line => trim(line))
  const nonEmptyLines = trimmedLines.filter(line => line !== '')
  
  return nonEmptyLines.join('\n')
}

const fileContent = `
  line 1
    line 2
  line 3

  line 4
`

const processed = processFileContent(fileContent)
console.log(processed)
// line 1
// line 2
// line 3
// line 4

Handling CSV Data

typescript
import { trim } from 'radash'

function processCSVLine(line: string) {
  const columns = line.split(',')
  return columns.map(column => trim(column))
}

const csvLine = '  Alice  ,  25  ,  alice@example.com  '
const processed = processCSVLine(csvLine)
console.log(processed) // ['Alice', '25', 'alice@example.com']

Handling Query Parameters

typescript
import { trim } from 'radash'

function parseQueryString(queryString: string) {
  const params = new URLSearchParams(queryString)
  const result: Record<string, string> = {}
  
  for (const [key, value] of params.entries()) {
    result[key] = trim(value)
  }
  
  return result
}

const queryString = 'name=  Alice  &email=  alice@example.com  &age=  25  '
const parsed = parseQueryString(queryString)
console.log(parsed) // { name: 'Alice', email: 'alice@example.com', age: '25' }

Handling Environment Variables

typescript
import { trim } from 'radash'

function getEnvVar(key: string, defaultValue = '') {
  const value = process.env[key] || defaultValue
  return trim(value)
}

// Simulate environment variables
process.env.API_URL = '  https://api.example.com  '
process.env.DATABASE_URL = '  postgresql://localhost:5432/mydb  '
process.env.SECRET_KEY = '  my-secret-key  '

console.log(getEnvVar('API_URL')) // 'https://api.example.com'
console.log(getEnvVar('DATABASE_URL')) // 'postgresql://localhost:5432/mydb'
console.log(getEnvVar('SECRET_KEY')) // 'my-secret-key'
console.log(getEnvVar('NON_EXISTENT', 'default')) // 'default'

Handling Log Messages

typescript
import { trim } from 'radash'

function formatLogMessage(level: string, message: string, context?: any) {
  const trimmedMessage = trim(message)
  const timestamp = new Date().toISOString()
  
  return {
    timestamp,
    level,
    message: trimmedMessage,
    context
  }
}

const logEntry = formatLogMessage('INFO', '  User login successful  ', { userId: 123 })
console.log(logEntry)
// {
//   timestamp: '2023-12-31T12:00:00.000Z',
//   level: 'INFO',
//   message: 'User login successful',
//   context: { userId: 123 }
// }

Handling Template Strings

typescript
import { trim } from 'radash'

function processTemplate(template: string, data: Record<string, any>) {
  const processedTemplate = trim(template)
  
  return processedTemplate.replace(/\{\{(\w+)\}\}/g, (match, key) => {
    const value = data[key] || ''
    return trim(String(value))
  })
}

const template = `
  Hello {{name}},
  Welcome to {{company}}!
`

const data = {
  name: '  Alice  ',
  company: '  Tech Corp  '
}

const result = processTemplate(template, data)
console.log(result)
// Hello Alice,
// Welcome to Tech Corp!

Handling Multiline Text

typescript
import { trim } from 'radash'

function processMultilineText(text: string) {
  const lines = text.split('\n')
  const trimmedLines = lines.map(line => trim(line))
  const nonEmptyLines = trimmedLines.filter(line => line !== '')
  
  return nonEmptyLines.join('\n')
}

const multilineText = `
  Line 1
    Line 2
  Line 3

  Line 4
`

const processed = processMultilineText(multilineText)
console.log(processed)
// Line 1
// Line 2
// Line 3
// Line 4

Notes

  1. Whitespace: Removes spaces, tabs, newlines, carriage returns, etc.
  2. Only Trims Ends: Only removes whitespace from the beginning and end, keeps whitespace in the middle
  3. Empty String: An empty string or a string with only whitespace returns an empty string
  4. Immutability: Returns a new string, does not modify the original string
  5. Performance: Very fast operation, suitable for frequent use

Differences from Other Methods

  • String.trim(): Native method, same functionality
  • trim(): String trimming method provided by radash
  • trimStart(): Only removes whitespace from the start
  • trimEnd(): Only removes whitespace from the end

Practical Application Scenarios

  1. User Input Processing: Clean up leading and trailing whitespace from user input
  2. Form Validation: Validate if form fields are empty
  3. File Processing: Clean up leading and trailing whitespace in file content
  4. API Processing: Clean up strings in API responses
  5. Configuration Processing: Clean up values in configuration files

Released under the MIT License.