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

时间:2016-03-04 12:30:44

标签: javascript html regex replace

假设我有以下字符串:

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>"

假设Text1,Text2,Text3,Text4是随机字符串

我在下面试过但是搞砸了:

text.replace(/<ins>(.*?)<\/p><p>/g, '</p><p><ins>');

由于

其他解释

看看这个:

<ins>Text1</p><p>Text2 </ins>

以上是错误的。它应该是:

Text1</p><p><ins>Text2 </ins>

2 个答案:

答案 0 :(得分:0)

您可以删除所有<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>

答案 1 :(得分:0)

请尝试以下正则表达式:

.

REGEX说明:

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

通过这种方式,每个捕获组的位置在正则表达式的帮助下移动。