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

335
Visualizações
Remove string between two characters using no regex Javascript

I'm trying to remove a sentence from a text file that I'm uploading through an Input file. I need to remove all sentences that are between '/' and '/' so comments line basically. Also all the single line comments such as '//' but I took care of it already. For that I'm not allowed to use any regex or replace function. Is there anyone who can help me on that ? Thanks

class Inpute extends Component{
  constructor(props){
    super(props);
    this.state = {
      fileName: '',
      fileContent: ''
    };
  }

  handleFile = e =>{
    const file = e.target.files[0];
    const reader = new FileReader();
    reader.readAsText(file);
    reader.onload = () => {
      this.setState({fileName: file.name, fileContent: reader.result});
      if(reader.result.includes('//')){
        var newText = reader.result
        newText = newText
                .split('\n')
                .filter(x => !x.includes('\/\/'))
                .join('\n')

        this.setState({fileName: file.name, fileContent: newText})
      }
    }
    reader.onerror = () =>{
      console.log('File Error : ', reader.error)
    }
  }
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

Split string by /. Parts that you need to delete are all in odd indexes so filter them out and join this array back into string.

const string = 'asdasada a/kkkkkkkk/a sdad asda s/xxxxx/s dasd';

const arr = string.split('/').filter((_, index) => index%2 === 0);

console.log(arr.join(''));

UPDATE

I have changed my example to filter only comments

const line = 'asdasada a/*kkkkkkkk*/a sdad asda s/*xxxxxs dasd x asda sd\n' +
    'asdas */das a// asdasda\n' +
    'x/*bbbbb*/c ad';
let prevPart = null;
let haveDoubleSlashes = false;

const cleaned = line.split('/').map(part => {

    // single line comments
    if (haveDoubleSlashes || part === '') {
        haveDoubleSlashes = true;

        if (part.includes('\n')) {
            part = '\n' + part.split('\n')[1];
            haveDoubleSlashes = false;
        } else {
            part = null;
        }

        return part;
    }

    /* multiline comments */
    if (part.startsWith('*') && part.endsWith('*')) {
        prevPart = null;
        return null;
    }

    if (prevPart !== null) {
        part = '/' + part;
    }

    prevPart = part;

    return part;
}).filter(part => part !== null).join('');

console.log(cleaned);

about 4 years ago · Juan Pablo Isaza Relatório

0

If all you care about is if the line contains two solidus characters (/), just filter on that:

const sample = `blah blah // blah blah\nblah blah /blah blah/ blah\nblah blah blah`;
const lines = sample.split('\n');
const good = lines.filter(x => 
  // [...x] makes the line an array of characters
  // reduce runs for each character, aggregating the result. 
  // agg is the aggregation, cur is the current character
  // Here it's just counting the number of /s and returning false if there are
  // fewer than two
  [...x].reduce((agg, cur) => agg = cur === '/' ? agg + 1 : agg, 0) < 2
  
);
console.log(good.join('\n'));

about 4 years ago · Juan Pablo Isaza Relatório

0

function stripMultilineComments(str) {
  let posOpen;
  let posClose;

  while ((posOpen = str.indexOf('/*')) !== -1) {

    posClose = Math.max(
      0, str.indexOf('*/', (posOpen + 2))
    ) || (str.length - 2);

    str = [
      str.substring(0, posOpen),
      str.substring(posClose + 2),
    ].join('');
  }
  return str;
}
function stripSingleLineComment(str) {
  let idx;
  if (
    (str.trim() !== '') &&
    ((idx = str.indexOf('//')) !== -1)
  ) {
    str = str.substring(0, idx);
  }
  return str;
}

function stripComments(value) {
  return stripMultilineComments(
    String(value)
  )
  .split('\n')
  .map(stripSingleLineComment)
  .join('\n');
}
const sampleData = `
  Lorem ipsum dolor sit amet/*, consectetur adipiscing elit,
  sed do eiusmod tempor incididunt*/ ut labore et dolore
  magna aliqua. // Ut enim ad minim veniam,
  quis nostrud exercitation ullamco laboris/*nisi ut 
  aliquip //ex ea commodo consequat*/. Duis aute irure dolor
  in reprehenderit// in voluptate velit esse cillum dolore
  eu fugiat nulla pariatur.// Excepteur sint occaecat
  /*cupidatat non //proident, */sunt in culpa qui officia
  deserunt mollit anim id est laborum.
`;

console.log(
  stripComments(sampleData)
);
console.log(
  stripComments(sampleData) === `
  Lorem ipsum dolor sit amet ut labore et dolore
  magna aliqua. 
  quis nostrud exercitation ullamco laboris. Duis aute irure dolor
  in reprehenderit
  eu fugiat nulla pariatur.
  sunt in culpa qui officia
  deserunt mollit anim id est laborum.
`);
.as-console-wrapper { min-height: 100%!important; top: 0; }

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