Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

200
Visualizações
Place string based on the format on an Array

Hi all sorry if the title is not right but i don't know how to put it in a title haha, my first post!

explanation: I have a javascript code in a file and i want to put it as text in an Array! also heads up, i am using React-ts

Basically the js file:

console.log('test me')
const data = 'my data'
const numbData = 1233
const myObj = {data: 123123}
const myArr = ['ewqeqw', '132312']
function myFunc(param) {
    console.log(param)
}
myFunc('testFunc')

What i tried:

  const [updated, setUpdate] = useState<boolean>(false);
  const [file, setFile] = useState();
  const areaRef = useRef<HTMLTextAreaElement | null>(null);
  const codeRef = useRef<HTMLParagraphElement | null>(null);

  const reader = new FileReader();

  function handleChange(event: any) {
    setFile(event.target.files[0]);
  }

  reader.addEventListener('loadend', function () {
    document.getElementById('newText').innerHTML = reader.result;
    setUpdate(true);
  });

  if (file) {
    reader.readAsText(file);
  }

  if (updated) {
    let data = codeRef.current?.innerText;
    let bodyTextArray = data?.split(/(\n)/);
    console.log(data);
    console.log(bodyTextArray);
  }

What i get : Console Log result

What i want:

["console.log('test me')", "const data = 'my data'",
 "const numbData = 1233", "const myObj = {data: 123123}", 
 "const myArr = ['ewqeqw', '132312']", "function myFunc(param) {
    console.log(param) }", "myFunc('testFunc')"
]

Basically every peice of code (variable declaration, functions...) on it's own!

Thank you and any solution would be be appreciated!

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

There's no need to use regex in split function. You can simply do this:

let bodyTextArray = data?.split('\n');
about 4 years ago · Juan Pablo Isaza Relatório

0

It will be much easier if you put each statement on a single line (including your myFunc function). Then you can just split on newlines:

TS Playground

function splitLines (input: string, skipEmpty = true): string[] {
  const lines: string[] = [];

  // split on regular or windows new lines
  for (const line of input.trim().split(/\r?\n/)) {
    // if the line is empty, skip it
    if (skipEmpty && !line.trim()) continue;
    lines.push(line);
  }

  return lines;
}

const text = `
console.log('test me')
const data = 'my data'
const numbData = 1233
const myObj = {data: 123123}
const myArr = ['ewqeqw', '132312']
function myFunc(param) { console.log(param) }
myFunc('testFunc')
`;

console.log(splitLines(text));

Compiled JS from the TS playground:

"use strict";
function splitLines(input, skipEmpty = true) {
    const lines = [];
    // split on regular or windows new lines
    for (const line of input.trim().split(/\r?\n/)) {
        // if the line is empty, skip it
        if (skipEmpty && !line.trim())
            continue;
        lines.push(line);
    }
    return lines;
}
const text = `
console.log('test me')
const data = 'my data'
const numbData = 1233
const myObj = {data: 123123}
const myArr = ['ewqeqw', '132312']
function myFunc(param) { console.log(param) }
myFunc('testFunc')
`;
console.log(splitLines(text));

If you don't put each statement on one line, you'll have to write you own logic for determining where each "part of your code" begins and ends in the string, and split on that logic.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda