使用正则表达式修改标签位置

Modify tag position with regex

本文关键字:标签 位置 修改 正则表达式      更新时间:2023-09-26

假设我有以下字符串:

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>