Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

201
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda