简体   繁体   中英

Replacing strings with inline html

I have a few keywords within a paragraph of text that need to be replaced by inline html dynamically. What would be the best way to go about this, using jQuery?

eg:

<p> 
Lorem :XXXX: dolor sit amet,  
consetetur :YYYY: elitr.
</p> 

should end up like:

<p> 
Lorem <span class="XXXX"></span> dolor sit amet, 
consetetur <span class="YYYY"></span> elitr.
</p> 

You don't really need jQuery for this, but I'm guessing you are already using it elsewhere on the page. Assuming the text inside the p tag is just regular text and you aren't trying to parse arbitrary HTML, you could do something like this

var item = $('p');
var htmltext = item.text();
htmltext = htmltext.replace(/:(\w+):/g, '<span class="$1"></span>');
item.html(htmltext);

This is also assuming "p" is the selector you want. Also assuming the pattern isn't always ":XXXX:" You may have to adjust the RegEx depending on what your desired goal is.

You don't need to load framework for this, simple pure JS solution:

var el = document.getElementsByTagName('p')[0];
var replacements = [':XXXX:', ':YYYY:'];

for (var i = 0; i < replacements.length; i++) {
    el.innerHTML = el.innerHTML.replace(replacements[i], '<span>' + replacements[i] + '</span>');
}

https://jsfiddle.net/6ung9610/1/

OR using regex:

var el = document.getElementsByTagName('p')[0];
el.innerHTML = el.innerHTML.replace(/(:\w+:)/g, '<span>$1</span>');

https://jsfiddle.net/6ung9610/3/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM