1

I want to replace some text in a jQuery string with images for example :

//original string
str = "This is a message from peter to john";

//After replacement
str = "This is a message from <img src='peter.jpg'> to <img src='john.jpg'>";

In php it can be done like this:

$string = strtr($str, array('peter'=>'<img src="peter.jpg" />', 'john'=>'<img src="john.jpg" />'));

Please is there a similar way to do this in jQuery just like the php method. Or any better idea to achieve this?

3
  • this answer to one of your previous questions is in essence what you are looking for Commented May 30, 2016 at 17:30
  • This really has very little (if anything) to do with jQuery. Commented Jul 3, 2016 at 22:55
  • Have you at least tried Googling this on your own? This is the type of question that can be solved by quickly consulting the JS documentation. Commented Jul 3, 2016 at 23:02

2 Answers 2

3

Use replace() method

var str = "This is a message from peter to john";
str = str.replace(/\b(?:peter|john)\b/g, "<img src='$&.jpg'>");
console.log(str)

Sign up to request clarification or add additional context in comments.

4 Comments

I think I prefer your method its easier. But what if the texts I want to replace has some characters like this ":peter;" or ":john;" How do I escape the : and ;
@KANAYOAUSTINKANE : /:(?:peter|:john);/g ,
But I end up having this <img src=':peter;.jpg' /> instead of <img src='peter.jpg' /> please how do I take out the : and ;?
@KANAYOAUSTINKANE : do it like : str.replace(/:(peter|john);/g, "<img src='$1.jpg'>");
2

Use javascript replace() method like this

var str = "This is a message from peter to john";
str = str.replace("peter","<img src='peter.jpg'>").replace("john","<img src='john.jpg'>");
console.log(str);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.