Home > Back-end >  javascript replace all specific string convert img tag
javascript replace all specific string convert img tag

Time:11-11

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>

CodePudding user response:

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);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

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>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

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)
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related