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

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

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 Denunciar

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 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