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

106
Vistas
javascript replace all specific string convert img tag

Need help with an algorithm logic.

<p>hello :love: my name is :mad: john, I am from :world: Germany.</p>

There is a string of type . What I want is to get a result like this:

<p>hello <img src="love"/> my name is <img src="mad"/> john, I am from <img src="world"/> Germany.</p>

What algorithm can I do this with?

Actually, what I want to do is to find the custom emoji in the message and turn it into an img tag. this is the code i tried, but this code only converts the first emote it finds

customEmojis.map((item) => {
                        const emoji = `:${item.short_names[0]}:`;
                        if (newMessage.includes(emoji)) {
                          const preEmojiMessage = newMessage.slice(
                            0,
                            newMessage.indexOf(emoji)
                          );
                          postEmojiMessage = newMessage.slice(
                            newMessage.indexOf(emoji) + emoji.length,
                            newMessage.length
                          );
                          newMessage = preEmojiMessage;
                          image = (
                            <img style={{ width: 25 }} src={item.imageUrl} />
                          );
                        } else {
                          return newMessage;
                        }
                      });



<p>
  {newMessage}
  {image !== undefined && image}
  {postEmojiMessage}
</p>
about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

you just need to do a .replace on the string, and in the regex, you need to return the substring without the ":" characters.

More info on .replace: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#specifying_a_string_as_a_parameter

let originalString = "<p>hello :love: my name is :mad: john, I am from :world: Germany.</p>";

let newString = originalString.replace(/(:)([a-zA-Z]*)(:)/g,'<img src="$2" />');

console.log(newString);

about 4 years ago · Juan Pablo Isaza Denunciar

0

I'd do something like this

document.getElementById("app").innerHTML = `
<p id="test">hello :love: my name is :mad: john, I am from :world: Germany.</p>
`;

let text = document.getElementById("test").innerHTML;
console.log("text", text); // logs hello :love: my name is :mad: john, I am from :world: Germany.

function parseText(text) {
  const strToMatch = text.match(/:[^ ]*:/g); // match everything between ":" if not containing the space char
  console.log("strToMatch", strToMatch); // logs [":love:", ":mad:", ":world:"]
  return strToMatch;
}

const toReplace = parseText(text);

for (const word of toReplace) {
  const replaceWith = `<img src="${word.substring(1, word.length-1)}"/>` // removes ":" before and after
  text = text.replace(word, replaceWith)
}
console.log(text) // logs hello <img src="love"/> my name is <img src="mad"/> john, I am from <img src="world"/> Germany. 
<!DOCTYPE html>
<html>

<head>
    <title>Parcel Sandbox</title>
    <meta charset="UTF-8" />
</head>

<body>
    <div id="app"></div>

    <script src="src/index.js">
    </script>
</body>

</html>

about 4 years ago · Juan Pablo Isaza Denunciar

0

In this problem, you are aiming at placing the text between two colons inside the img tag.

You can do this with basic iteration using while loop as I have done in my code below.

// function to put text under colon in the img
function imageTag(string){

    let n = string.length
    let index = 0
    let returnString = ""
    
    while(index < n){

        // If the string have colon on the index, then iterate till the closing colon
        if(string[index] == ':'){
            let tag = ""
            index += 1
            while(string[index] != ':'){
                tag += string[index]
                index += 1
            }
            returnString += `<img src="${tag}"/>`
        }

        // else just add the character to the string that will be returned
        else
            returnString += string[index]

        index += 1
    }
    
    return returnString
    
}

let initial = "<p>hello :love: my name is :mad: john, I am from :world: Germany.</p>"
let final = imageTag(initial)

console.log(final)

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