<!-- The text field -->
<input type="text" value="" id="barcode">
<!-- 1234567890123456789012 copy and paste to test -->
function trimAndCopyHandler(event) {
  
  // The barcode input text box
  const barcodeBox = event.target
  // The barcode input string
  const barcodeText = barcodeBox.value
  
  // if the string is shorter than 22 chars then exit
  if (barcodeText.length < 22) return
  
  const start = 6 // start index in string
  const end = 19 // end index in string
  
  // Select the text field
  barcodeBox.select()
  barcodeBox.setSelectionRange(start, end)
  
  // assign extracted section of barcode to trimmedString
  const trimmedString = barcodeText.slice(start, end)
  
  // Copy the trimmedString
  navigator.clipboard.writeText(trimmedString)
  
  // using template strings `${my variable here}`
  alert(`Copied ${barcodeText} to clipboard`)
  
  // clear the text box
  barcodeBox.value = ''
}

// find and assign the trim button element to 'trimAndCopyButton'.
const barcode = document.querySelector('#barcode')

// add a listener to the barcode element, which fires
// onchange and executes the trimAndCopyHandler
barcode.addEventListener('change', trimAndCopyHandler)
Run Pen

External CSS

This Pen doesn't use any external CSS resources.

External JavaScript

This Pen doesn't use any external JavaScript resources.