【发布时间】:2016-04-24 08:28:53
【问题描述】:
我创建了 regex,它应该在相邻的 <span> 标记内移动文本。
const fix = (string) => string.replace(/([\S]+)*<span([^<]+)*>(.*?)<\/span>([\S]+)*/g, "<span$2>$1$3$4</span>")
fix('<p>Given <span class="label">Butter</span>'s game, the tree counts as more than one input.</p>')
// Results in:
'<p>Given <span class="label">Butter's</span> game, the tree counts as more than one input.</p>'
但是,如果我将一个字符串传递给它,其中没有文本触及 <span> 标记,则需要几秒钟才能运行。
我正在 Chrome 和 Electron 上对此进行测试。
【问题讨论】:
-
用正则表达式解析 HTML?嗯。
-
如果您只关心
span,请使用:-<span([^<]+)>(.*?)<\/span>..regex101.com/r/fL9rG0/1 -
我还看到
([^<]+)*一个额外的*我认为不需要 -
还有一件事:- 如果
</span>不存在,您的正则表达式将出现灾难性的回溯 -
不要这样做是最好的答案。使用任何methods for parsing HTML in JavaScript。
标签: javascript regex performance