替换jQuery字符串中的文本(Replacing text in a jQuery string)
我想用图像替换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方法一样。 或者更好的想法来实现这一目标?
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?
最满意答案
使用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)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)
更多推荐
发布评论