Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/85.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
查找并删除文本,然后使用jquery或javascript插入图像_Javascript_Jquery_Emoticons - Fatal编程技术网

查找并删除文本,然后使用jquery或javascript插入图像

查找并删除文本,然后使用jquery或javascript插入图像,javascript,jquery,emoticons,Javascript,Jquery,Emoticons,我试图用jquery或javascript将文本替换为图像。比如说 <div id="log"> <p>this is a :) happy face</p> <p>this is a :( sad face</p> <p>these are :/ x( :P other faces</p> </div> 这是一张快乐的脸 这是一张悲伤的脸 这些是:/x(:p其他面 我尝试了几件事,但要么替换了

我试图用jquery或javascript将文本替换为图像。比如说

<div id="log">
<p>this is a :) happy face</p>
<p>this is a :( sad face</p>
<p>these are :/ x( :P other faces</p>
</div>

这是一张快乐的脸

这是一张悲伤的脸

这些是:/x(:p其他面

我尝试了几件事,但要么替换了整个字符串,要么浏览器不呈现图像,而是显示html

this is a <img src="happy.png"> face
这是一张脸
这是一个聊天应用程序,我正在使用它,而且我是一个相当新的聊天应用程序,因此,如果您能在代码中包含一些解释,它将提供帮助:)

可能看起来像(使用jQuery):

$('div#log').find('p').html(函数(html){
返回html.replace(':)','';
});
很明显,这应该变得更复杂一些。我可以想象一个查找对象,将字符串链接到图像,例如:

var myMap = {
    '\\:\\)': 'happy.png',  // need to escape those for regex
    '\\:\\(': 'sad.png',
    '\\:\\/': 'other.png'
};

$('div#log').find('p').html(function( _, html ) {
    for(var face in myMap) {
        html = html.replace( new RegExp( face, 'g' ), '<img src="' + myMap[ face ] + '"/>' );
    }
    return html;
});
var myMap={
“\\:\ \)”:“happy.png”,//需要对正则表达式进行转义
“\\:\”(“:”sad.png“,
“\\:\ \/”:“other.png”
};
$('div#log').find('p').html(函数(#,html){
用于(myMap中的变量面){
html=html.replace(新的RegExp(face,'g'),“”);
}
返回html;
});

您尝试过这样做吗

<div id="log">
<p id='my'>this is a :) happy face</p>
<p>this is a :( sad face</p>
<p>these are :/ x( :P other faces</p>
</div>

var p = $('#my').html();
var r = p.replace(':)', '<img src="happy.jpg">');
$('#my').html(r);

这是一张:)快乐的脸

这是一张悲伤的脸

这些是:/x(:p其他面

var p=$('#my').html(); var r=p.replace(':)',''; $('my').html(r);

在这里摆弄:

+1很好的解决方案。你不需要转义
/
。事实上,我不确定如果表达式中有无效的转义字符序列会发生什么。可能是它然后尝试按字面意思匹配
\
,所以它甚至会“中断”表达式。非常好。您的代码运行得非常好,是一个健壮的解决方案,非常感谢您!只需稍加修改,您的代码就运行得非常好。我没有向段落标记添加id,而是使用了p:last选择器。因为段落是动态添加的,并且它们不是唯一的,因此它们不会获得id。
<div id="log">
<p id='my'>this is a :) happy face</p>
<p>this is a :( sad face</p>
<p>these are :/ x( :P other faces</p>
</div>

var p = $('#my').html();
var r = p.replace(':)', '<img src="happy.jpg">');
$('#my').html(r);