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

143
Views
Javascript RegExp Allow Spaces Inside Pattern

I need to replace all "*text*" into "<strong>text</strong>"

when passing text = "normal text *words to be bolded* continue normal text" it doesn't work because of the spaces, it works only for single-word text.

wanted result: "normal text <strong>words to be bolded</strong> continue normal text"

result: "normal text *words to be bolded* continue normal text"

I need this function to work for whatever the text is:

function bold(text){
    reg = /\*(\w+)\*/g
    return text.replaceAll(reg, "<strong>" + text.split(reg)[1] + "</strong>")
}
about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

You can use the array split method.

const str = "word1 word2 pla pla";
const newStr = [];
str.split(" ").forEach((val) => {
  newStr.push(`<strong>${val}</strong> `);
});
console.log(newStr);

about 4 years ago · Juan Pablo Isaza Report

0

You should allow a set of characters to be there. Right now, you have the sequence of characters fixed.

function bold(text){
    reg = /\*([\w\s]+)\*/g
    return text.replaceAll(reg, "<strong>" + text.split(reg)[1] + "</strong>")
}
about 4 years ago · Juan Pablo Isaza Report

0

I assume that by 'words to be bolded', you are trying to match anything that is not asterisk.

function bold(text){
    let reg = /\*([^\*]*)\*/g;
    return text.replaceAll(reg, "<strong>$1</strong>")
};
let result = bold("normal1 *bold1 including space!* normal2 *bold2, including space?* normal3"); 
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!