使用正则表达式修改标签位置
Modify tag position with regex
假设我有以下字符串:
var text = "<p>Some text <ins>Text1</p><p>Text2 </ins><ins>Some other text </ins>and another text<ins>Text3</p><p>Text4 </ins></p>"
我需要将上面的字符串清理成
var text = "<p>Some text Text1</p><p><ins>Text2 </ins><ins>Some other text </ins>and another text Text3</p><p><ins>Text4 </ins></p>"
假设文本 1、文本 2、文本 3、文本 4 是随机字符串
我在下面尝试过,但只是搞砸了:
text.replace(/<ins>(.*?)<'/p><p>/g, '</p><p><ins>');
谢谢
附加说明
看看这个:
<ins>Text1</p><p>Text2 </ins>
以上是错误的。它应该是:
Text1</p><p><ins>Text2 </ins>
请尝试以下正则表达式:
function posChange() {
var text = "<p>Some text <ins>Text1</p><p>Text2 </ins><ins>Some other text </ins>and another text<ins>Text3</p><p>Text4 </ins></p>";
var textnew = text.replace(/(<ins>)([^<]+)(<'/p><p>)([^<]+)/g, '$2$3$1$4');
alert(textnew);
}
posChange()
正则表达式解释:
/(<ins>) 1st capturing group (i.e: <ins>)....$1
([^<]+) 2nd capturing group (i.e: Text1)....$2
(<'/p><p>) 3rd capturing group (i.e: </p><p>)..$3
([^<]+) 4th capturing group (i.e: Text2 )...$4
/g match all occurrences
根据要求,对于每个匹配项:
Original String: $1 $2 $3 $4
should be replaced with
New String: $2 $3 $1 $4
通过这种方式,每个捕获组的位置在正则表达式的帮助下发生了变化。
您可以删除所有<ins>
:
text = text.replace(/<ins>/g, '');
然后替换每个以 </ins>
结尾且不包含任何带有 <ins>
总和的标签和此字符串的字符串:
var matches = text.match(/[^<>]+<'/ins>/g)
for (i = 0; i < matches.length; i++) {
text = text.replace(matches[i], '<ins>' + matches[i]);
}
结果:
<p>Some text Text1</p><p><ins>Text2 </ins><ins>Some other text </ins>and another textText3</p><p><ins>Text4 </ins></p>
相关文章:
- 注入<脚本>标签给它一个合适的位置
- 如何使用位置获取滚动功能获取 HTML 中的元素标签
- 如何找到内部标签的位置并将其聚焦
- 使用正则表达式修改标签位置
- 为什么鼠标光标和红线在将缩放 0.5 添加到正文标签时位置不同
- 无论如何可以检查 html 标签的位置
- 离开悬停后如何将P标签保持在上一个位置
- 如何阅读新标签位置.href.match?使用 Javascript
- 垂直标签:删除没有jQuery或固定位置属性的UL和DIV中断
- 使用 javascript 查找文本中 HTML 标签的位置,最好不使用正则表达式
- 背景大小设置为包含的正文标签上的位置和缩放元素
- 窗口位置主题标签语法错误在问号后未读取
- 停止浮动标签重置回原始位置
- 是否存在标签“1”的优选位置;标签为“;,使用jQuery Mobile
- 如何使用散列标签(“一个名字”)去页面上的位置,但在顶部说明一个固定的元素
- 如何修复标签的位置,使它们不会在DevExpress js图表中重叠
- AngularJS+Ionic:标签取决于滚动位置
- Highcharts条形图数据标签位置
- 道场堆叠条形/柱形图表标签位置不正确
- Safari扩展获取标签位置或标识符