我想用图像替换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" />'));
请用类似php方法的方法在jQuery中执行类似的操作。还是有更好的主意来实现这一目标?
使用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)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句