问题描述
请大伙儿,我是Jquery的新手。自上周以来我一直在寻找合适的帮助,但我找不到任何帮助。我想用jQuery替换带笑脸图片的文本,但我不知道如何运行它。例如,我想用我感觉< img src ='happy_face替换为我感觉:happy; >。 gif'/> 和He is :sick; 替换为他是< img src ='sick.gif'/> 。这是我迄今得到的,但它仍然显示文本,而不是图像:
:): (
< script src =js / jscript.js>< / script>
< script>
var emotes = [
[':happy;' ,'happy.gif'],
[':sick;','sick.gif']
];
函数applyEmotesFormat(body){
for (var i = 0; i< emotes.length; i ++){
body = body.replace(new RegExp(emotes [i] [0],'gi'),'< img src =emotes /'+ emotes [i] [1] +'>');
}
return body;
}
预先感谢
其实很简单。 $ b您只需要一行就可以在HTML中查找和替换字符串实例:
$(body)。html($(body)。html()。replace(/ :happy; / g,'< div class =happy-face>< / div>')); $ b
这将 $(body)。html()设置为 $(body)。html() with :happy; 替换为< div class =happy-face>< / div> / code>。
/:happy; / g 是RegEx来查找字符串:happy; 全局( g )
Please Guys, I am new to Jquery. I have been searching for a suitable help since last week but I can't find any. I want to replace a text with a smiley image using jquery but I have no idea how to run this. For example, I want this text "I am feeling :happy;" to be replaced with "I am feeling <img src='happy_face.gif' />" and "He is :sick;" to be replaced with "He is <img src='sick.gif' />".Here is what I have gotten so far but it still displays the text instead of the image:
:) :( <script src="js/jscript.js"></script> <script> var emotes = [ [':happy;', 'happy.gif'], [':sick;', 'sick.gif'] ]; function applyEmotesFormat(body){ for(var i = 0; i < emotes.length; i++){ body = body.replace(new RegExp(emotes[i][0], 'gi'), '<img src="emotes/' + emotes[i][1] + '">'); } return body; }
Thanks in advance
It is actually quite simple.You only need one line to find and replace string instances in the HTML:$("body").html($("body").html().replace(/:happy;/g,'<div class="happy-face"></div>'));
This sets $("body").html() to the $("body").html() with :happy; replaced with <div class="happy-face"></div>.
/:happy;/g is RegEx to find the string :happy; globally (g)
https://jsfiddle.net/heowqt1u/2/
这篇关于使用Jquery替换带有笑脸图像的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!