Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

255
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!