用HTML标记+ \ n替换关闭的HTML标记 [英] Replacing closing HTML tags with HTML tag + \n
问题描述
我试图用结束标记+换行符代替通常结束的html标记,我在这里找到了类似的帖子,没有一个真正帮助我完成想要的事情.
I'm trying to replace generally closing html tags with the closing tag + a line break, i found similar posts here on SO, none really helped me to accomplish what I'm looking for.
</li>
将为</li>\n
<img some property />
将是<img some property />\n
我通过以下功能设法在php中做到了这一点,效果很好:
I managed to do that in php with the following funtion, which works well:
public static function addLBinHTML($htmlcode){
$pattern= array('~(</.*?>)~','(/>)');
$replace= array('${1} Hallo \n ','/>\n ');
return preg_replace($pattern, $replace, $htmlcode);
}
我正在尝试在JavaScript/jQuery中执行相同的操作,但未能获取变量(在php regex ${1}
中).
I'm trying to do the same in JavaScript / jQuery and I'm failing on getting the variable(in php regex ${1}
).
我尝试使用.split .join和.replace,并且我认为.replace是正确的方法.
I tried with .split .join and with .replace, and I think .replace is the right way to go.
这就是我得到的(我最后一次也是最接近的尝试)
Here is what I got (my last and hopefully closest attempt)
function setLinebreaks(taID){
var strContent = $('#'+taID).val();
var regex = new RegExp("</.*?>", "gi");
strContent.replace(regex, "${1} \n ")
.replace(/\/>/g,'/> \n ');
console.log(strContent);
$('#'+taID).val(strContent);
}
预先感谢您的帮助
推荐答案
您必须使用方括号捕获正则表达式,分配替换后的字符串,然后将${1}
替换为$1
:>
You have to capture the regular expression with brackets, assign the replaced string and replace ${1}
by $1
:
var regex = new RegExp("(</.*?>)", "gi");
strContent = strContent.replace(regex, "$1 \n ")
.replace(/\/>/g,'/> \n ');
或者您可以简单地将replace
方法放入val
函数中.
Or you can simply put the replace
methods into the val
function.
这篇关于用HTML标记+ \ n替换关闭的HTML标记的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!