Home > Enterprise >  How to make tool converter with javascript split()
How to make tool converter with javascript split()

Time:07-09

I have bulk data in written text like this:

[email protected]:token1 | Time = US | Alfabet = abc | EndToken = July 22, 2022 | Generate Since = July 2021 
[email protected]:token2 | Time = US | Alfabet = bcd | EndToken = July 11, 2022 | Generate Since = June 2021
[email protected]:token3 | Time = UK | Alfabet = dca | EndToken = July 11, 2022 | Generate Since = June 2020

How to make a tool with javascript by inserting bulk data into a text area then the result is in a modal popup with text result like this:

Convert Result/expected output:

 No.1
Email: [email protected]
Token: token1
Time = US
Alfabet = abc
EndToken = July 22, 2022
Generate Since = July 2021
 
 No.2
Email: [email protected]
Token: token2
Time = US
Alfabet = bcd
EndToken = July 11, 2022
Generate Since = June 2021

 No.3
Email: [email protected]
Token: token3
Time = UK
Alfabet = dca
EndToken = July 11, 2022
Generate Since = June 2020

I made the input textarea look like this:

function convert() {
    document.getElementById("convertResult").value = " No.1\nEmail: [email protected]\nToken: token1\nTime = US\nAlfabet = abc\nEndToken = July 22, 2022\nGenerate Since = July 2021\n\n No.2\nEmail: [email protected]\nToken: token2\nTime = US\nAlfabet = bcd\nEndToken = July 11, 2022\nGenerate Since = June 2021\n\n No.3\nEmail: [email protected]\nToken: token3\nTime = UK\nAlfabet = dca\nEndToken = July 11, 2022\nGenerate Since = June 2020\n\n";
}

  let buttonCopy = document.getElementById("copyResult"),
      input = document.getElementById("convertResult");

  buttonCopy.addEventListener("click", function(event) {
    event.preventDefault();
    input.select();
    document.execCommand("copy");
    alert("Result copied");
  });
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css">
  <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.slim.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
  
  <form >
  <div >
    <label for="exampleFormControlTextarea1">Paste bulk text data bellow</label>
      <textarea  id="exampleFormControlTextarea1" rows="8">
      [email protected]:token1 | Time = US | Alfabet = abc | EndToken = July 22, 2022 | Generate Since = July 2021
      [email protected]:token2 | Time = US | Alfabet = bcd | EndToken = July 11, 2022 | Generate Since = June 2021
      [email protected]:token3 | Time = UK | Alfabet = dca | EndToken = July 11, 2022 | Generate Since = June 2020
      </textarea>
  </div>

  <button type="button" onclick="convert()"  data-toggle="modal" data-target="#exampleModalCenter">
  Convert
</button>
</form>

<div  id="exampleModalCenter" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
  <div  role="document">
    <div >
      <div >
        <h5  id="exampleModalLongTitle">Convert Result</h5>
        <button type="button"  data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div >
        <textarea id="convertResult"  id="exampleFormControlTextarea1" rows="8"></textarea>
      </div>
      <div >
        <button type="button"  data-dismiss="modal">Close</button>
        <button type="button" id="copyResult" >Copy Result</button>
      </div>
    </div>
  </div>
</div>

The value entered will be like the code sample above, and the expected result will be like the code in the "Convert Result:" section.

CodePudding user response:

This script will do that:

let $btn = document.querySelector('#convert')
$btn.addEventListener('click', function() {
    let inputArr = document.querySelector('#exampleFormControlTextarea1').value.split('\n');
    let $result = document.querySelector('#exampleFormControlTextarea2')
    let number = 1    
    let final = []

    for (row of inputArr) {
        let rowArr = row.split(' | ')
        let first = rowArr.shift().split(':')
        let nrString = ` No.`   number
        let mail = `Email: ${first[0]}`
        let token = `Token: ${first[1]}`

        rowArr.unshift(nrString, mail, token);
        rowArr = rowArr.join('\n')
        final.push(rowArr)
        number  
    }

    let finalText = final.join('\n\n')
    $result.value = finalText
})

See https://jsfiddle.net/qg2Lez0b/1/

You have to rename the second textarea to #exampleFormControlTextarea2 and give a id to the button convert.

CodePudding user response:

One approach is as follows, with explanatory comments in the code:

// defining a named function to handle the formatting/conversion of the entered data,
// using Arrow function syntax and passing in the Event Object ('e') from the (later)
// use of EventTarget.addEventListener():
const convertFormat = (e) => {
    // caching the element into which the source data is entered:
    const source = document.querySelector('#exampleFormControlTextarea1'),
      // retrieving that entered data, and using String.prototype.trim() to
      // remove the leading and trailing white-space:
      sourceData = source.value.trim(),
      // splitting the sourceData into an array of individual entries/records,
      // using String.prototype.split() with a regular expression literal, to
      // split the string on a character-sequence of a word-boundary (\b) at the
      // end of each line ($); this uses the 'm' and 'g' flags; 'g' (global) to
      // match all occurrences and 'm' (multiline) to treat '$' as the end-of-line
      // character, rather than end-of-string.
      // Once this array is created we pass it to Array.prototype.map(), again
      // using an Arrow function, to call String.prototype.trim() on every array-element
      // of the created Array:
      records = sourceData.split(/\b$/gm).map((v) => v.trim());

    // if we have a truthy records result:
    if (records) {
      // we create a variable 'res' by iterating over the records Array with Array.prototype.map()
      // to create a new Array based on the inital Array:
      let res = records.map(
        // here we pass in a reference to the current Array-element ('arr') and the index of the
        // current Array-element ('i'):
        (arr, i) => {
          // using destructuring assignment to create a variable called 'mail' and another that
          // takes all remaining entries from the Array called 'keyValues'; to assign these variables
          // we split the current Array-element ('arr') on a character sequence of one-or-more 
          // white-space characters (\s ) followed by a '|' character (escaped with a back-slash
          // because it's a special character in regular expressions) and followed by more white-
          // space characters:
          let [mail, ...keyValues] = arr.split(/\s \|\s /),
              // we then use more destructuring assignments; here we split the '[email protected]:token1'
              // String at the ':' character, the first entry of the created array will be assigned to the
              // 'email' variable, and the String that followed the ':' character will be assigned to the
              // 'token' variable:
              [email, token] = mail.split(':'),
            // here we create a template-literal string, as that allows us to interpolate JavaScript
            // variables and line-breaks into the String:
            // so first we have a line-break, and create a String of ' ' with the interpolated value of
            // i (the Array-element's index) plus 1 (the index is zero-based, and you seem to want a
            // 1-based count), followed by another line-break and the 'Email:' String followed by
            // another interpolated variable:
            resultString = `
 ${i 1},
Email: ${email}
Token: ${token}`;

          // here we iterate over the keyValues array, with an Arrow function passing in a reference
          // to the current Array-element ('kv'):
          keyValues.forEach(
            (kv) => {
              // in this anonymous function, we split the kv array-element String on the '=' character,
              // and then trim the resulting Array entries; those entries are then passed to the variables
              // 'key' and 'val':
              let [key, val] = kv.split('=').map((v) => v.trim());
              // we then append these details to the resultString, again using a template-literal:
              resultString  = `
${key}: ${val}`;
            });
          // we return the resultString:
          return resultString;
        // and we join all the Array elements together - using Array.prototype.join() - with a line-break
        // using a template-literal:
        }).join(`
        `);
      // we retrieve the '#output' element, and update its value:
      document.querySelector('#output').value = res;
    }
  },
  // we find the first/only <button> element on the page (adjust the selector to suit your use-case):
  convertButton = document.querySelector('button');

// And here we use EventTarget.addEventListener() to bind the convertFormat() function (note the lack
// of parentheses) as the event-handler for the 'click' event on the <button>:
convertButton.addEventListener('click', convertFormat);
*,
 ::before,
 ::after {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}

main {
  border: 1px solid #000;
  display: grid;
  gap: 0.5em;
  margin-block: 1em;
  margin-inline: auto;
  padding-block: 0.25em;
  padding-inline: 0.5em;
  width: clamp(10rem, 60vw, 1000px);
}

textarea {
  min-height: 10rem;
}
<main>
  <label for="exampleFormControlTextarea1">Paste bulk text data below</label>
  <textarea id="exampleFormControlTextarea1">
  [email protected]:token1 | Time = US | Alfabet = abc | EndToken = July 22, 2022 | Generate Since = July 2021
  [email protected]:token2 | Time = US | Alfabet = bcd | EndToken = July 11, 2022 | Generate Since = June 2021
  [email protected]:token3 | Time = UK | Alfabet = dca | EndToken = July 11, 2022 | Generate Since = June 2020
</textarea>
  <button>Convert</button>
  <textarea id="output"></textarea>
</main>

JS Fiddle demo.

References:

  • Related