且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

JQuery替换< p>中的文本部分与< img>

更新时间:2023-02-23 13:20:49

使用 $ c>:

  $('p')。each(function(){
this.innerHTML = this .innerHTML.replace(/ \bok\b / g,'< img src =ok.pngalt =good word/>')
})

我使用 / \bok\b / code>令牌将不匹配。 \b 表示字边界。



这是一个小提琴


I have this code in my body :

<p>
    hello ok hello no
<p>

<p>
    ok hello ok ko 
<p>    

I want to replace for each <p> the text 'ok' by <img> tag <img src="ok.png" alt="good word"/>

Is it possible to do this ?

Note : i must apply this function for others texts who can contain apostrophe and/or quote

Use each:

$('p').each(function() {
    this.innerHTML = this.innerHTML.replace(/\bok\b/g, '<img src="ok.png" alt="good word"/>')
})

I used /\bok\b/ so that something like token won't match. \b means "word boundary."

Here's a fiddle.