KANAYO AUGUSTIN UG
KANAYO AUGUSTIN UG

Reputation: 2188

Replacing text in a jQuery string

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?

Upvotes: 1

Views: 225

Answers (2)

Pranav C Balan
Pranav C Balan

Reputation: 115262

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)

Upvotes: 3

Mohammad
Mohammad

Reputation: 21499

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

Upvotes: 2

Related Questions