我想用图像替换jQuery字符串中的一些文本,例如:

//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'>";

在php中可以这样做:
$string = strtr($str, array('peter'=>'<img src="peter.jpg" />', 'john'=>'<img src="john.jpg" />'));

请注意,在jQuery中是否有类似于php方法的方法来执行此操作。或者有更好的办法来实现这个目标?

最佳答案

使用replace()方法

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

关于javascript - 替换jQuery字符串中的文本,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37530982/

10-12 13:07
查看更多