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

258
Visualizações
Mark specific words with asterisks (Javascript)

I have an array of objects with a set of certain words like entities. For example :

footnotes: [
  { sourceText: 'red'},
  { sourceText: 'green'},
  { sourceText: 'yellow'},
  { sourceText: 'purple'},
  { sourceText: 'gray'},
  { sourceText: 'blue'}
]

And I have some random sentences. For example: 'I drive a red car among green fields and look at the gray sky'

The goal is to mark words with asterisks according to the object of entities:

'I drive a red* car among green** fields and look at the gray*** sky'

I'm trying to do this in a loop with silce and Regexp but I can't concatenate the string correctly

How can this be done ?

Here is my code

footnotes = [{
    sourceText: "red",
    solve: false
  },
  {
    sourceText: "green",
    solve: false
  },
  {
    sourceText: 'yellow',
    solve: false
  },
  {
    sourceText: "purple",
    solve: false
  },
  {
    sourceText: "grey",
    solve: false
  },
  {
    sourceText: "blue",
    solve: false
  }
]

starGenerate = function(count) {
  let result = ''
  
  for (let i = 0; i < count; i++) {
    result += '*'
  }
  
  return result
},


let post = {
  id: 21321,
  data: {},
  lead: 'I drive a red car among green fields and look at the gray sky'
}


post.check = function() {
  let str, concat = ''
  let self = this;
  let starcounter = 0

  for (let i = 0; i < self.entities.length; i++) {
    let reg = new RegExp(`${self.entities[i].sourceText}`);

    if (match = reg.exec(self.lead) && self.entities[i].solve === false) {
      concat = self.lead.replace(reg, `${self.entities[i].sourceText + starGenerate(++starcounter)}`)
      self.entities[i].solve = true
    }
  }
}

post.entities = footnotes
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

You can do this with one regular expression (using |), and then use the callback argument of replace to insert the asterisks. I would prepare the replacement text for each word and place it in an object keyed by word. Your function starGenerate is not really needed, as there is the repeat method.

function putAsterisks(footnotes, sentence) {
    let alternatives = footnotes.map(({sourceText}) => sourceText).join("|");
    let replacements = Object.fromEntries(footnotes.map(({sourceText}, i) => 
        [sourceText, sourceText + "*".repeat(i + 1)]
    ));
    let regex = RegExp("\\b(" + alternatives + ")\\b", "gi");
    return sentence.replace(regex, m => replacements[m]);
}

// Example:
let footnotes = [{ sourceText: 'red'}, { sourceText: 'green'}, { sourceText: 'yellow'}, { sourceText: 'purple'}, { sourceText: 'gray'}, { sourceText: 'blue'}];
let sentence = 'I drive a red car among green fields and look at the gray sky with a red moon';

console.log(putAsterisks(footnotes, sentence));

This assumes that the source texts do not contain characters that have a special meaning in regular expressions. If this could happen, then use this answer to first escape those words.

about 4 years ago · Juan Pablo Isaza Relatório

0

You can do the same without regex by splitting your string and using map among all the words. This works fine as long as there is no further punctuation in your input string

const footnotes=[{sourceText:"red",solve:!1},{sourceText:"green",solve:!1},{sourceText:"yellow",solve:!1},{sourceText:"purple",solve:!1},{sourceText:"grey",solve:!1},{sourceText:"blue",solve:!1}];

const input = 'I drive a red car among green fields and look at the grey sky'
const footnotesIndex = footnotes.reduce( (acc,i) => (acc[i.sourceText] = i.solve,acc),{});
let star=1
const result = input.split(" ").map( word =>footnotesIndex[word] != undefined ? word + "*".repeat(star++) : word).join(" ");
console.log(result);

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