Reverse String

String reversal and text processing tool

反转示例

按字符反转

原文:Hello World

结果:dlroW olleH

按单词反转

原文:Hello World

结果:World Hello

按行反转

原文:第一行
第二行

结果:第二行
第一行

Tool Overview: String Reverse Tool

String reversal is a fundamental text processing operation that completely reverses the order of characters in a string. This tool supports multiple reversal modes including full reversal, line-by-line reversal, and word-by-word reversal, suitable for text processing, data transformation, and programming practice scenarios.

What Is String Reverse Tool?

String Reverse Tool cleans and transforms text quickly for reuse.

How to Use

  1. Paste the text to process.
  2. Select the required options.
  3. Copy the processed result.

Common Use Cases

  • Clean logs and config text
  • Preprocess content before editing
  • Batch text cleanup

❓ FAQ

Q1: Need to keep spaces?
A: Adjust the options to preserve whitespace.

Q2: Large input is slow?
A: Split into smaller parts.

Q3: How to export?
A: Copy the output directly.

✨ Key Features

  • 🔄 Multiple Reversal Modes: Supports full reversal, line-by-line reversal, word-by-word reversal
  • 🌐 Unicode Support: Correctly handles Unicode characters like Chinese and emojis
  • Real-time Processing: Input text shows reversal results instantly
  • 📋 One-click Copy: Reversal results can be directly copied for use
  • 🔧 Batch Processing: Supports batch reversal of multi-line text

📖 Usage Examples

Full Reversal

Input Text:

Hello World!

Reversal Result:

!dlroW olleH

Chinese Text Reversal

Input Text:

Welcome to ToolMi

Reversal Result:

iMlooT ot emocleW

Line-by-line Reversal

Input Text:

First line of text
Second line of text
Third line of text

Reversal Result:

txet fo enil tsriF
txet fo enil dnoceS
txet fo enil drihT

Word-by-word Reversal

Input Text:

Hello World Welcome

Reversal Result:

Welcome World Hello

🎯 Application Scenarios

1. Data Processing

Using string reversal in data processing and transformation:

// Data masking processing
function maskSensitiveData(data) {
  // Reverse sensitive data as simple obfuscation
  const reversed = data.split('').reverse().join('')
  return btoa(reversed) // Then Base64 encode
}

// Usage example
const sensitiveInfo = "Sensitive user information"
const masked = maskSensitiveData(sensitiveInfo)
console.log('Masked:', masked)

// Decryption function
function unmaskSensitiveData(maskedData) {
  const decoded = atob(maskedData)
  return decoded.split('').reverse().join('')
}

const original = unmaskSensitiveData(masked)
console.log('Original data:', original)

2. Text Games

Creating word games and puzzles:

// Palindrome detector
function isPalindrome(str) {
  const cleaned = str.toLowerCase().replace(/[^a-z0-9]/g, '')
  const reversed = cleaned.split('').reverse().join('')
  return cleaned === reversed
}

// Test examples
console.log(isPalindrome("racecar")) // true
console.log(isPalindrome("A man a plan a canal Panama")) // true
console.log(isPalindrome("race a car")) // false

// Word puzzle generator
function generateWordPuzzle(sentence) {
  const words = sentence.split(' ')
  const puzzles = words.map(word => {
    return {
      original: word,
      reversed: word.split('').reverse().join(''),
      hint: `${word.length} characters`
    }
  })
  return puzzles
}

// Usage example
const puzzles = generateWordPuzzle("ToolMi Online Tools")
console.log(puzzles)
// [
//   { original: "ToolMi", reversed: "iMlooT", hint: "6 characters" },
//   { original: "Online", reversed: "enilnO", hint: "6 characters" },
//   { original: "Tools", reversed: "slooT", hint: "5 characters" }
// ]

3. Programming Practice

For algorithm learning and programming practice:

// Multiple implementations of string reversal

// Method 1: Using built-in methods
function reverseString1(str) {
  return str.split('').reverse().join('')
}

// Method 2: Using loop
function reverseString2(str) {
  let result = ''
  for (let i = str.length - 1; i >= 0; i--) {
    result += str[i]
  }
  return result
}

// Method 3: Using recursion
function reverseString3(str) {
  if (str === '') return ''
  return reverseString3(str.substr(1)) + str.charAt(0)
}

// Method 4: Using two pointers
function reverseString4(str) {
  const arr = str.split('')
  let left = 0
  let right = arr.length - 1
  
  while (left < right) {
    [arr[left], arr[right]] = [arr[right], arr[left]]
    left++
    right--
  }
  
  return arr.join('')
}

// Performance testing
function performanceTest(str) {
  const methods = [reverseString1, reverseString2, reverseString3, reverseString4]
  const methodNames = ['Built-in', 'Loop', 'Recursion', 'Two Pointers']
  
  methods.forEach((method, index) => {
    const start = performance.now()
    const result = method(str)
    const end = performance.now()
    console.log(`${methodNames[index]}: ${end - start}ms`)
  })
}

// Test
const testString = "This is a long string for performance testing".repeat(1000)
performanceTest(testString)

4. Text Art

Creating text art and effects:

// Text animation effects
class TextAnimation {
  constructor(element, text) {
    this.element = element
    this.originalText = text
    this.currentText = text
  }

  // Character-by-character reverse animation
  async reverseAnimation(speed = 100) {
    const chars = this.originalText.split('')
    
    for (let i = 0; i < chars.length; i++) {
      // Reverse first i characters
      const reversed = chars.slice(0, i + 1).reverse()
      const remaining = chars.slice(i + 1)
      this.currentText = [...reversed, ...remaining].join('')
      
      this.element.textContent = this.currentText
      await this.delay(speed)
    }
  }

  // Wave reverse effect
  async waveReverse(speed = 50) {
    const chars = this.originalText.split('')
    const length = chars.length
    
    for (let wave = 0; wave < length; wave++) {
      const newChars = [...chars]
      
      // Create wave effect
      for (let i = 0; i < length; i++) {
        const distance = Math.abs(i - wave)
        if (distance <= 2) {
          // Reverse characters within wave range
          const start = Math.max(0, wave - 2)
          const end = Math.min(length, wave + 3)
          const section = chars.slice(start, end).reverse()
          newChars.splice(start, section.length, ...section)
        }
      }
      
      this.element.textContent = newChars.join('')
      await this.delay(speed)
    }
    
    // Final complete reversal
    this.element.textContent = chars.reverse().join('')
  }

  delay(ms) {
    return new Promise(resolve => setTimeout(resolve, ms))
  }
}

// Usage example
const textElement = document.getElementById('animated-text')
const animation = new TextAnimation(textElement, 'ToolMi Online Platform')

// Start animation
animation.reverseAnimation(200)

5. Data Validation

For data validation and integrity checking:

// Simple data integrity checker
class DataIntegrityChecker {
  // Generate checksum
  static generateChecksum(data) {
    const reversed = data.split('').reverse().join('')
    const combined = data + reversed
    
    // Simple hash algorithm
    let hash = 0
    for (let i = 0; i < combined.length; i++) {
      const char = combined.charCodeAt(i)
      hash = ((hash << 5) - hash) + char
      hash = hash & hash // Convert to 32-bit integer
    }
    
    return Math.abs(hash).toString(36)
  }

  // Verify data integrity
  static verifyIntegrity(data, checksum) {
    const calculatedChecksum = this.generateChecksum(data)
    return calculatedChecksum === checksum
  }
}

// Usage example
const originalData = "Important business data"
const checksum = DataIntegrityChecker.generateChecksum(originalData)
console.log('Checksum:', checksum)

// Verify data
const isValid = DataIntegrityChecker.verifyIntegrity(originalData, checksum)
console.log('Data integrity:', isValid ? 'Valid' : 'Invalid')

// Simulate data tampering
const tamperedData = "Important business data modified"
const isTamperedValid = DataIntegrityChecker.verifyIntegrity(tamperedData, checksum)
console.log('Tampered data verification:', isTamperedValid ? 'Valid' : 'Invalid')

🔧 Technical Details

Unicode Character Processing

Correctly handling Unicode character reversal:

Basic Character Reversal:

  • ASCII characters: Direct byte reversal
  • Unicode characters: Reverse by Unicode code points
  • Emojis: Need special handling for composite characters

Complex Character Handling:

// Correctly handle Unicode character reversal
function reverseUnicode(str) {
  // Use Array.from to correctly split Unicode characters
  return Array.from(str).reverse().join('')
}

// Test different types of characters
console.log(reverseUnicode("Hello World 🌍"))
// Output: 🌍 dlroW olleH

Performance Optimization

Performance comparison of different reversal methods:

Method Performance Ranking:

  1. Built-in methods: split('').reverse().join('')
  2. Two-pointer algorithm: Suitable for large strings
  3. Loop construction: High memory efficiency
  4. Recursive method: Concise but poor performance

💡 Usage Tips

  • Unicode Processing: Use Array.from() to correctly handle composite characters
  • Performance Considerations: Two-pointer algorithm recommended for large texts
  • Memory Optimization: Avoid creating too many temporary strings
  • Special Characters: Pay attention to handling newlines and special symbols

⚠️ Important Notes

  • Character Encoding: Ensure correct handling of UTF-8 encoded characters
  • Composite Characters: Emojis and other composite characters need special handling
  • Performance Impact: Very long text reversal may affect performance
  • Memory Usage: Pay attention to memory consumption when processing large texts

🚀 Getting Started

  1. Input Text: Enter the text to be reversed in the input box
  2. Choose Mode: Select full reversal, line-by-line reversal, or word-by-word reversal
  3. View Results: Reversal results are displayed in real-time in the output area
  4. Copy for Use: Click "Copy" button to copy results to clipboard
  5. Batch Processing: Supports batch reversal operations for multi-line text

Tip: This tool processes locally on the client side and does not upload your text content to the server, ensuring privacy and security.