[英]Replacing strings with inline html
I have a few keywords within a paragraph of text that need to be replaced by inline html dynamically. 我在一段文本中有一些关键字需要动态替换为内联html。 What would be the best way to go about this, using jQuery? 使用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. 你真的不需要jQuery,但我猜你已经在页面的其他地方使用它了。 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 假设p
标记内的文本只是常规文本,并且您没有尝试解析任意HTML,您可以执行类似这样的操作
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. 这也是假设“p”是你想要的选择器。 Also assuming the pattern isn't always ":XXXX:" You may have to adjust the RegEx depending on what your desired goal is. 同时假设模式并不总是“:XXXX:”您可能必须根据您期望的目标调整RegEx。
You don't need to load framework for this, simple pure JS solution: 您不需要为这个简单的纯JS解决方案加载框架:
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/ 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/ https://jsfiddle.net/6ung9610/3/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.