Javascript Regex to look for characters and wrap text with span dynamically

只谈情不闲聊 提交于 2021-02-05 12:22:33

问题


So I'm trying to replace this:

<h1>My Title &lt;INTRO&gt;</h1>

With this:

<h1>My Title <span>&lt;INTRO&gt;</span></h1>

But...

In a way that dynamically looks for all instances of text wrapped in &lt; ... &gt; and wraps that in span tags.

Something like the code below, but I can't get the regex right.

str = str.replace(/(?<=&lt;)\r\n(?=&gt;)/, "<span>$1</span>");

回答1:


You can use the following regex:

(&lt;[\s\S]*?&gt;)

And replace with:

<span>$1</span>

See DEMO

Js Code:

var str = "<h1>My Title &lt;INTRO&gt;</h1>"
str = str.replace(/(&lt;[\s\S]*?&gt;)/, "<span>$1</span>");
alert(str);


来源:https://stackoverflow.com/questions/30852689/javascript-regex-to-look-for-characters-and-wrap-text-with-span-dynamically

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!