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

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

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 Denunciar

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 Denunciar

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