How to wrap around part of text inside an element?

2019-09-11 04:45发布

Let's say I have the sentence:

Lorem ipsum dolor sit amet, consectetur adipiscing elit.

inside a <p> tag. I would like to somehow use javascript to create an element around the word amet, e.g.:

Lorem ipsum dolor sit <span>amet</span>, consectetur adipiscing elit.

Is there some sort of way to do this? In the real-world application for this, I won't know what text I want to have an element around, so I can't just modify the HTML.

1条回答
迷人小祖宗
2楼-- · 2019-09-11 05:33

One option is using replace method.

$('p').html(function(index, oldHtml){
   return oldHtml.replace(/(amet)/g, '<span>$1</span>');
});

http://jsfiddle.net/YxMvq/

查看更多
登录 后发表回答