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

144
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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