JavaScript 字符串 : get content of two standing next to each other pieces of content and wrap them together

标签 javascript html regex

我正在尝试创建一个小脚本来包装文本的某些部分,例如<p>像这样的标签:<p>... 'displayed text'[popup content] ...</p>在跨度包装器中。

最终结果是这样的:

<span class='wrapper'>
  displayed text
  <span class='popup'>popup content</span>
</span>

目前我可以像这样找到并替换撇号之间的文本:

some_string.replace(/'(.*?)'/g,'<span>$1</span>');

但我真的很想包装 popup content先分开然后用displayed text把它包起来在wrapper里面元素。

这可能吗?

最佳答案

当然 - 这个怎么样?

some_string.replace(/'(.*?)'\[(.*?)\]/, "$1<span class='popup'>$2</span>");

如果正则表达式的两部分可以用空格分隔,则在它们之间添加 \s*:

/'(.*?)'\s*\[(.*?)\]/

关于JavaScript 字符串 : get content of two standing next to each other pieces of content and wrap them together,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56991052/

相关文章:

javascript - 我听说全局变量不好,我应该使用什么替代解决方案?

javascript - 检查是否有任何数字单独重复超过 N 次

javascript - 如果他们之前有文章,则丢弃正则表达式中的标记

html - 如何将 Bootstrap 应用于 asp.net 中的编辑器?

Jquery 计数 2 个元素之间的项目

excel - 如何让 REGEXMATCH 在一系列单元格中查找多个术语,而不是查看一个单元格?

php - 为所有物理/化学/生物单位进行正则表达式匹配?

javascript - 通过ajax从本地目录解析gz文件中的json - angularJS

html - 什么条件会绑定(bind)位置 : fixed element to its parent's box?

javascript - 如何使用 JS 检查字符串是否会成为有效的 html ID?