[英]regex replace first element
I have the need to replace a HTML string's contents from one <br>
to two. 我需要将HTML字符串的内容从一个<br>
替换为两个。 But what I can't achieve is when I have one tag following another one: 但是我无法实现的是,当我在另一个标签之后放置一个标签:
(<br\\s*\\/?>)
will match all the tags in this text: 将匹配此文本中的所有标签:
var text = 'text<BR><BR>text text<BR>text;'
will match and with the replace I will have 将匹配并替换,我将拥有
text = text.replace.replace(/(<br\s*\/?>)>/gi, "<BR\/><BR\/>")
console.log(text); //text<BR/><BR/><BR/><BR/>text text<BR/><BR/>text;"
Is there a way to only increment one tag with the regex? 有没有办法只用正则表达式增加一个标签? And achieve this: 并实现以下目标:
console.log(text); //text<BR/><BR/><BR/>text text<BR/><BR/>text;"
Or I only will achieve this with a loop? 还是我只能通过循环来实现?
You may use either 您可以使用
var text = 'text<BR><BR>text text<BR>text;' text = text.replace(/(<br\\s*\\/?>)+/gi, "$&$1"); console.log(text); // => text<BR><BR><BR>text text<BR><BR>text;
Here, (<br\\s*\\/?>)+/gi
matches 1 or more sequences of <br>
s in a case insensitive way while capturing each tag on its way (keeping the last value in the group beffer after the last it, and "$&$1"
will replace with the whole match ( $&
) and will add the last <br>
with $1
. 在这里, (<br\\s*\\/?>)+/gi
以不区分大小写的方式匹配1个或多个<br>
序列,同时捕获每个标记(保持组中的最后一个值在最后一个之后)它,然后"$&$1"
将替换为整个匹配项( $&
),并将最后一个<br>
添加为$1
。
Or 要么
var text = 'text<BR><BR>text text<BR>text;' text = text.replace(/(?:<br\\s*\\/?>)+/gi, function ($0) { return $0.replace(/<br\\s*\\/?>/gi, "<BR/>") + "<BR/>"; }) console.log(text); // => text<BR/><BR/><BR/>text text<BR/><BR/>text;
Here, the (?:<br\\s*\\/?>)+
will also match 1 or more <br>
s but without capturing each occurrence, and inside the callback, all <br>
s will get normalized as <BR/>
and a <BR/>
will get appended to the result. 在这里, (?:<br\\s*\\/?>)+
也将匹配1个或多个<br>
但不捕获每次出现,并且在回调内部,所有<br>
都将被标准化为<BR/>
并且<BR/>
将被附加到结果中。
You can use negative look ahead (<br\\s*\\/?>)(?!<br\\s*\\/?>)/
to increment only the last tag if there are any consecutive: 您可以使用否定的前瞻(<br\\s*\\/?>)(?!<br\\s*\\/?>)/
来递增最后一个标记,如果有连续的话:
var text = 'text<BR><BR>text text<BR>text;' text = text.replace(/(<br\\s*\\/?>)(?!<br\\s*\\/?>)/gi, "<BR\\/><BR\\/>") console.log(text);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.