Batch of search and replace with CSV

by Ukjin Yang

HTML

<script src="https://unpkg.com/papaparse@latest/papaparse.min.js"></script>
<div class="flex flex-col w-full h-full p-2">
  <form id="replacer" onsubmit="return false" class="flex items-start">
    <div class="flex-1">
      <h2>Original Text</h2>
      <textarea name="original" cols="30" rows="10" class="block w-full h-full resize-y"></textarea>
    </div>
    <div class="flex-1">
      <h2>CSV to search and replace</h2>
      <textarea name="replaces" cols="30" rows="10" class="block w-full h-full resize-y"></textarea>
    </div>
  </form>
  <div class="flex-1 flex flex-col">
    <h2>Result</h2>
    <textarea readonly id="replaced" cols="30" rows="10" class="block w-full flex-1 resize-y"></textarea>
  </div>
</div>

Tailwind CSS

html, body {
  width: 100%;
  height: 100%;
  overflow: hidden;
}

JavaScript

document.addEventListener("DOMContentLoaded", () => {
  const $ = document.querySelector.bind(document), $$ = document.querySelectorAll.bind(document);
  
  const $replacer = $('#replacer'), $replaced = $('#replaced');
  
  $replacer.querySelectorAll('textarea').forEach(el => el.addEventListener('change', e => {
  	const data = new FormData($replacer);
    const replaces = Papa.parse(data.get('replaces'));
    let origin = data.get('original');
    if (!replaces || !replaces.data || !replaces.data.length) return;
    for (const row of replaces.data) {
    	if (row && row.length && row.length > 1)
    	origin = origin.replaceAll(row[0], row[1]);
    }
    $replaced.value = origin;
  }));
});