2

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?

e.g.:

<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> 

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

2 Comments

var $p = $('p'); var htmltext = $p.text();
Good point; that will reduce the likelihood that HTML will get in there for the RegEx comparison.
2

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/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.